首页 > 解决方案 > spring security loadUserByUsername 登录后用户名为空 url 几天不使用

问题描述

@Autowired
private BCryptPasswordEncoder passwordEncoder;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(cUserDetailService)
            .passwordEncoder(passwordEncoder);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/user/**").authenticated()
            .and()
            .csrf().disable()
            .formLogin()
            .usernameParameter("username")
            .passwordParameter("password")
            .successHandler(successHandler)
            .failureHandler(failureHandler)
            .and()
            .logout()
            .logoutSuccessHandler(logoutSuccessHandler)
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(authEntryPoint)
            .accessDeniedHandler(accessDeniedHandler)
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .maximumSessions(1)
            .maxSessionsPreventsLogin(false);
}


public class CUserDetailService implements UserDetailsService {

@Autowired
private UserDetailDataEntityRepository userDetailDataEntityRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    log.info("username: " + username + ", " );
    log.info(username == null);

    Optional<UserDetailDataEntity> optional = userDetailDataEntityRepository.findByUsername(username);
    if (optional.isPresent()) {
        return optional.get();
    } else {
        throw new UsernameNotFoundException(username);
    }
}

我将此配置用于我的 spring 安全性,并首先成功登录。但是我们发现如果几天没有人访问服务器(甚至是登录网址),然后再次登录,loadUserByUsername 用户名将为空并登录失败

仅供参考,我通过添加依赖项使用 redis 进行会话管理

        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>

登录请求是表单请求

标签: spring-securityspring-session

解决方案


推荐阅读