java - 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!
解决方案
推荐阅读
- docker - ip 地址可从 docker 主机访问,但不能从主机上运行的 docker 容器访问
- android - Glide 不会在没有扩展名的情况下加载 placeholder.com 图像
- c++ - reinterpret_cast 无效但 static_cast 很好
- ffmpeg - 控制台上的 DTS 垃圾邮件警告无效
- java - 如何对 ArrayList 中的对象进行排序?
- node.js - 为什么请求体为空,响应状态为404?
- azure - 使用 packer 和 azure devops 创建 vm 映像
- ruby - 如何传递方法参数用作哈希路径?
- reactjs - 创建一个自定义 SP WebPart,让用户在其中添加本机组件
- php - 用于 php 会话和 ajax 调用的 Redis 集群不保存会话