Java Spring Security HeaderPreAuthentication主体未从@AuthenticationPrincipal解析
我有一个现有的Spring引导应用程序,它对由第三方身份验证服务处理的web应用程序进行身份验证。与SiteMinder一样,第三方服务向HTTP请求中注入一个头,比如USER_头。我的任务是配置现有应用程序以提取此HTTP头,并通过Spring SecurityJava Spring Security HeaderPreAuthentication主体未从@AuthenticationPrincipal解析,java,spring,spring-security,spring-boot,pre-authentication,Java,Spring,Spring Security,Spring Boot,Pre Authentication,我有一个现有的Spring引导应用程序,它对由第三方身份验证服务处理的web应用程序进行身份验证。与SiteMinder一样,第三方服务向HTTP请求中注入一个头,比如USER_头。我的任务是配置现有应用程序以提取此HTTP头,并通过Spring Security@AuthenticatedPrincipal注释使生成的Auth对象可供MVC层的控制器使用 如前所述,该项目是一个Spring引导应用程序,版本为1.1.9.RELEASE,使用Java8 (下面显示的代码来自镜像功能的测试项目)
@AuthenticatedPrincipal
注释使生成的Auth对象可供MVC层的控制器使用
如前所述,该项目是一个Spring引导应用程序,版本为1.1.9.RELEASE,使用Java8
(下面显示的代码来自镜像功能的测试项目)
请注意,此应用程序仅为Java配置。不允许使用XML(由我的领导授权)
通过深入阅读和其他各种文章,我知道我需要使用RequestHeaderAuthenticationFilter
并将其注入过滤器链中,以从请求头获取用户名
过滤器:
public class HeaderAuthenticationFilter extends RequestHeaderAuthenticationFilter {
private static final Logger logger = LoggerFactory.getLogger(HeaderAuthenticationFilter.class);
private final String HEADER = "USER_HEADER";
public HeaderAuthenticationFilter() {
super();
this.setPrincipalRequestHeader(HEADER);
// This setting returns an HTTP 404 with no error message instead of an HTTP 500 with the "missing header" exception message
this.setExceptionIfHeaderMissing(false);
}
@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
logger.debug("Authorizing URI: " + request.getRequestURI());
try {
return super.getPreAuthenticatedPrincipal(request);
} catch(PreAuthenticatedCredentialsNotFoundException e) {
logger.error("Could not find request header " + HEADER + " in request", e);
return null;
}
}
}
你可以看到非常基本的过滤器
使用我现在拥有的代码,用户从HTTP请求中提取,通过预身份验证过程,其中预身份验证token由自定义AuthenticationManager创建,用户业务对象作为主体注入到令牌中,令牌最终分配给SecurityContext,具有:
SecurityContextHolder.getContext().setAuthentication(主体)
但是,当我用@AuthenticationPrincipal User User
注释我的控制器方法时,返回的用户对象是空的用户对象。当我将method参数更改为Authentication user
并显式调用user.getPrincipal()
时,用户对象就很好了。@AuthenticationPrincipal失败的原因是什么
谢谢,如果需要更多细节,请告诉我 未解析
@AuthenticationPrincipal
的原因是我没有用@EnableWebMvcSecurity
注释我的WebSecurityConfigureAdapter类
添加此注释解决了此问题