所以我将 Spring Security 与 Spring Boot 结合使用。我想制作自己的 AuthenticationProvider
,以我自己的方式使用数据库,所以我使用这个 authenticate
方法来实现:
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String email = authentication.getName();
String password = authentication.getCredentials().toString();
UserWithEmail userWithEmail = authService.getUserByEmail(email);
if (userWithEmail == null)
return null;
if (userWithEmail.getPassword().equals(password)) {
UsernamePasswordAuthenticationToken authenticated_user = new UsernamePasswordAuthenticationToken(userWithEmail, password, Arrays.asList(REGISTERED_USER_SIMPLE_GRANTED_AUTHORITY));
return authenticated_user;
} else {
return null;
}
}
如果我在表单中使用默认的/login 页面,效果很好,之后如果我将以下 ModelAttribute
添加到 Controller
中,它就会被正确填充使用 UserWithEmail
对象:
@ModelAttribute("userwithemail")
public UserWithEmail userWithEmail(){
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Object principal = authentication.getPrincipal();
if (principal instanceof UserWithEmail)
return (UserWithEmail) principal;
else
return null;
}
问题是,如果我点击/login?logout,它会正确显示我已注销,但如果我再次通过 Controller ,我仍然会得到与主体相同的 UserWithEmail
对象,并且它具有属性 authenticated=true
这是我的 Spring Security 的 Java 配置:
http
.formLogin()
.defaultSuccessUrl( "/" )
.usernameParameter( "username" )
.passwordParameter( "password" )
.and()
.logout().invalidateHttpSession(true).deleteCookies("JSESSIONID").permitAll().and()
.authorizeRequests()
.antMatchers("*/**").permitAll()
.antMatchers("/static/**").permitAll()
.antMatchers("/profile").hasRole(MyAuthenticationProvider.REGISTERED_USER_AUTH)
.and().authenticationProvider(getAuthProvider());
我是 Spring Security 的新手,所以也许我错过了一些东西......任何人都可以帮忙吗?
最佳答案
根据文档here for CSRF注销时必须使用 POST 以及用于攻击防护的 CSRF token 。
因为我使用的是自定义模板引擎,所以我必须从请求中拦截模型属性中的 CSRF token ,如下所示:
@ModelAttribute("crsf_token")
public CsrfToken getcrsfToken(HttpServletRequest request, Model model) {
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
return token;
}
因为它没有被复制到我的模板引擎的模型中。
关于java - 为什么 SpringSecurity 在注销后继续提供相同的经过身份验证的主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29866171/