首页 > 解决方案 > Spring security HttpServletRequest and SecurityContextHolder logout not working

问题描述

I am relatively new to Spring Security and I am attempting to create an endpoint for logging out an user. The code I have tried so far:

  public ResponseEntity<String> logout(HttpServletRequest request, HttpServletResponse response) {
//    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//    if (auth != null) {
//      new SecurityContextLogoutHandler().logout(request, response, auth);
//      System.out.println("logging out");
//      return new ResponseEntity<>(HttpStatus.OK);
//    }
    try {
      request.logout();
      System.out.println("successful logout");
    } catch (ServletException e) {
      e.printStackTrace();
    }
    return new ResponseEntity<>(HttpStatus.OK);
  }

My UserDetailsServiceImpl:

@Service
public class AccountDetailsServiceImpl implements UserDetailsService {
  private final AccountRepository accountRepository;

  public AccountDetailsServiceImpl(AccountRepository accountRepository) {
    this.accountRepository = accountRepository;
  }

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Account account = accountRepository.findByUsernameOrEmail(username, username);
    if (account == null) {
      throw new UsernameNotFoundException(username);
    }
    return new CustomUserDetails(account);
  }
}

My security configuration:

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().authorizeRequests()
        .antMatchers(HttpMethod.POST, securityConstraintsProperties.getSignUpUrl()).permitAll()
        .anyRequest().authenticated()
        .and()
        .addFilter(new JWTAuthenticationFilter(authenticationManager(), getApplicationContext(), securityConstraintsProperties))
        .addFilter(new JWTAuthorizationFilter(authenticationManager(), securityConstraintsProperties))
        // this disables session creation on Spring Security
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
  }

I have seen both possibilities in different Stackoverflow answers, but unfortunately none of them is working for me. When I perform a request after logging out, the request is still possible. How is that possible?

Thank you in advance!

标签: javaspring-securitylogout

解决方案


推荐阅读