在Resources中的ContainerRequestFilter中创建的访问对象

时间:2014-10-28 01:45:56

标签: jersey

如何使user对象可用于资源中的进一步处理

   @Priority(Priorities.AUTHENTICATION)
   public static class ResourceAllowedRequestFilter implements ContainerRequestFilter {
      private AuthorizationValidation authorizationValidation;

      public ResourceAllowedRequestFilter() {
         try {
            authorizationValidation = new AuthorizationValidation();
         } catch (Exception e) {

         }
      }

      @Override
      public void filter(ContainerRequestContext requestContext) throws IOException {
         if (userHeader == null) {
           throw new BadRequestException(Response.status(Status.BAD_REQUEST).build());
         } else {
           User user = authorizationValidation.isAuthorizationValid(userHeader)
         }
      }
   }

   @GET
   @Path("/{page}/{limit}")
   public Response getBooks() {
     Access user object created in ContainerRequestFilter
   }

1 个答案:

答案 0 :(得分:2)

Afaig,只有一种方法,名为注射 - 但多种方式使用注射。

这里有两种方法:

  1. 您可以实施/使用javax.ws.rs.core.SecurityContext。因此,您的用户必须实现java.security.Principal并使用@Context将SecurityContext注入您的资源。以下基本示例......

  2. 您还可以构建并注册Factory并将每个请求的用户注入您的资源。请访问jersey docs,或搜索@ stackoverflow。你会发现很多例子。

  3. SecurityContext(1)示例:

    <强> ContainerRequestFilter

    @Override
    public synchronized void filter(ContainerRequestContext request)
            throws IOException {
    
        final User user = authorizationValidation.isAuthorizationValid(userHeader)
    
        // impl 
        request.setSecurityContext( new MySecurityContext(user) );
    
        // or simple but not the best
        request.setSecurityContext( new SecurityContext() {
            @Override
            public boolean isUserInRole(String role) {
                return true; // check roles if you need ...
            }
            @Override
            public boolean isSecure() {
                return false; // check HTTPS
            }
            @Override
            public Principal getUserPrincipal() {
                return user; // return your user here - User must implement Principal
            }
            @Override
            public String getAuthenticationScheme() {
                return null; // ...
            }
        }
    }
    

    <强>资源

    @Context
    protected SecurityContext securityContext;
    
    @GET
    @Path("/{page}/{limit}")
    public Response getBooks() {
        User user = (User)securityContext.getUserPrincipal();
    }
    

    祝你有愉快的一天......