我使用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: