重新启动浏览器后,使用Spring Boot应用程序访问Web应用程序时,会删除“记住我的Cookie”

时间:2019-07-25 12:13:45

标签: spring spring-boot spring-security

我有一个使用Spring Security 5.0的Spring Boot应用程序,为此我无法在没有持久性的情况下正确设置记住我功能。

  1. 我登录并创建了记住我的cookie
  2. 如果我退出应用程序,但未关闭浏览器,则可以正常运行
  3. 如果我关闭浏览器然后再次打开它,记住我的cookie仍然在这里
  4. 重新打开浏览器,当我访问该应用程序的任何页面时,“记住我” cookie消失,并要求我再次登录。
  5. 使用新的登录名,将创建一个新的“记住我” cookie

这是安全配置:

@Configuration
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{

@Override
protected void configure(HttpSecurity http)throws Exception{
    http
        .authorizeRequests()
            .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/admin/**").hasRole("USER")
            .antMatchers("/backstage").hasRole("ADMIN")
        .and()    
            .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/admin")
        .and()
            .logout()
        .and()
            .rememberMe()
            .key("TopSecretSentence")
            .alwaysRemember(true)
        .and()
            .exceptionHandling()
            .accessDeniedPage("/")
        .and()
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .ignoringAntMatchers("/stripe/webhooks", "/zodomus-booking")
        .and()
            .httpBasic()
        .and()
            .sessionManagement()
            .invalidSessionUrl("/")
            .sessionAuthenticationErrorUrl("/login?logout");
}

@Autowired
private UserServiceImpl userDetailsService;

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

浏览器已关闭该字段:仅保留本地数据,直到您退出浏览器

最后,这是UserDetailsService的实现:

@Service
public class UserServiceImpl implements UserDetailsService {

@Autowired
UserRepository userRepository;

@Autowired
RoleRepository roleRepository;            

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    RentalWebsUser userInfo = userRepository.getUserByUsername(username);
    List<GrantedAuthority> authorities = roleRepository.getRolesByUsername(username);

    if(userInfo != null && !authorities.isEmpty()){

        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(userInfo.getPassword());
        User user = new User(userInfo.getUsername(), encodedPassword, authorities);

        return user;

    } else throw new UsernameNotFoundException("Wrong user/password");}     

}

这是带有第4步标头的请求的图像: request with the header for step 4

这是带有步骤4的cookie的图像,其中“记住我”已经消失了: cookies for step 4, where the remember me one has disappeared

这是登录后的第5步标题的图片,带有新的“记住我” cookie: headers for step 5, after the login, with the new remember me cookie

0 个答案:

没有答案