为了多种目的,我需要使用
SecurityContextHolder.getContext().getAuthentication()方法在我的控制器/服务中。
我确实将我的应用程序从XML配置的Spring应用程序(现在只有Java吐露)迁移到Spring 1.4.1,类似的方法以前也起过作用。
我在调用SecurityContextHolder.getContext().getAuthentication()时遇到了问题,例如在这个控制器中:
@RestController
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
@RequestMapping("utils")
public class UtilsController {
@RequestMapping(value = "/check_auth", method = RequestMethod.GET)
public Boolean getAuthState() throws SQLException {
if (SecurityContextHolder.getContext().getAuthentication() == null){
logger.info("Auth obj null");
}
if (SecurityContextHolder.getContext().getAuthentication().getName() != null && SecurityContextHolder.getContext().getAuthentication().getName() != "anonymousUser") {
return true;
} else return false;
}
}它总是返回null。不知道为什么匿名身份验证不起作用。
下面是Spring安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.formLogin()
.successHandler(ajaxSuccessHandler)
.failureHandler(ajaxFailureHandler)
.loginProcessingUrl("/authentication")
.passwordParameter("password")
.usernameParameter("username")
.and()
.logout()
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.csrf().disable()
// .anonymous().disable()
.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/admin/*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/user/*").access("hasRole('ROLE_USER')");
}我尝试过在控制器上使用和不使用@Secured注释。
.authorizeRequests()
// .anyRequest().anonymous()
.antMatchers("/utils").permitAll()与此设置有不同的变化。
发布于 2016-11-02 19:43:36
您得到的null是:
SecurityContextHolder.getContext().getAuthentication()因为您没有在安全配置中进行身份验证。
您可以添加一个简单的:
.authenticated()
.and()
// ...
.formLogin();以防你使用表单登录。
现在,在对每个请求进行身份验证之后,您应该获得null以外的其他内容。
以下是的一个示例:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
// ...
.formLogin();
}https://stackoverflow.com/questions/40356150
复制相似问题