我使用SecurityContextHolder在我的JAX-RS资源中获取用户名,并且可以正常工作:
@Path("/myresource")
public class MyResoure {
@Get
public String getUserName() {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
}
但是我想将SecurityContext注入到类字段中(以编写JUnit测试).我尝试了一些记录的方法:
使用javax.ws.rs.core.SecurityContext,我得到一个NullPointerException,因为securityContext始终为null.
@Path("/myresource")
public class MyResoure {
@Context
private javax.ws.rs.core.SecurityContext securityContext;
@Get
public String getUserName() {
return securityContext.getUserPrincipal().getName();
}
}
使用org.apache.cxf.security.SecurityContext(参见Apache CXF documentation)我得到一个NullPointerException,因为securityContext.getUserPrincipal()始终为null.
@Path("/myresource")
public class MyResoure {
@Context
private org.apache.cxf.security.SecurityContext securityContext;
@Get
public String getUserName() {
return securityContext.getUserPrincipal().getName();
}
}
使用org.apache.cxf.jaxrs.ext.MessageContext(参见Apache CXF documentation)我得到一个NullPointerException,因为messageContext.getSecurityContext().getUserPrincipal()始终为null.
@Path("/myresource")
public class MyResoure {
@Context
private org.apache.cxf.jaxrs.ext.MessageContext messageContext;
@Get
public String getUserName() {
return messageContext.getSecurityContext().getUserPrincipal().getName();
}
}
使用javax.servlet.http.HttpServletRequest,我得到一个NullPointerException,因为httpServletRequest.getUserPrincipal()始终为null.
@Path("/myresource")
public class MyResoure {
@Context
private javax.servlet.http.HttpServletRequest httpServletRequest;
@Get
public String getUserName() {
return httpServletRequest.getUserPrincipal().getName();
}
解决方法:
获取用户名
> javax.ws.rs.core.SecurityContext,
> org.apache.cxf.security.SecurityContext,
> org.apache.cxf.jaxrs.ext.MessageContext或
> javax.servlet.http.HttpServletRequest
我必须将SecurityContextHolderAwareRequestFilter添加到我的springSecurityFilterChain中.
弹簧配置:
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<security:filter-chain-map path-type="ant">
<security:filter-chain pattern="/**" filters="securityContextPersistenceFilter,authenticationProcessingFilter,securityContextHolderAwareRequestFilter,anonymousProcessingFilter,exceptionTranslationFilter,filterSecurityInterceptor" />
</security:filter-chain-map>
</bean>
使用安全命名空间配置或Java Configuration默认添加过滤器,请参阅Spring Security documentation:
- servlet-api-provision Provides versions of HttpServletRequest security methods such as isUserInRole() and getPrincipal() which are implemented by adding a SecurityContextHolderAwareRequestFilter bean to the stack. Defaults to true.