我使用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 提供HttpServletRequest安全方法的版本,例如isUserInRole()和getPrincipal(),这些方法通过将SecurityContextHolderAwareRequestFilter bean添加到堆栈中来实现。默认为true。
  • 09-29 21:08