2017-11-02 13 views
0

私は、認証と認可を使用して埋め込みJettyで私の最初のRestful Webサービスを作成しています。私はユーザーオブジェクト(Employee)を注入するフィルタを持っていますResteasyProviderFactory.pushContext()@Contextアノテーションを使用してサービスBeanを取得しますが、オブジェクトを試すものは常にnullです。私はどんな種類の助けにも感謝します。私の理解ではREST-ful webservice @Context注入は常にnullを返します

@PreMatching 
public class AuthenticationHandler implements ContainerRequestFilter { 


@Inject private PxCredentialService credentialService; 


@Override 
public void filter(ContainerRequestContext requestContext) throws IOException { 

    Response faultresponse = createFaultResponse(); 

    String authorization = requestContext.getHeaderString("Authorization"); 
    String[] parts = authorization.split(" "); 
    if (parts.length != 2 || !"Basic".equals(parts[0])) { 
     requestContext.abortWith(createFaultResponse()); 
     return; 
    } 

    String decodedValue = null; 
    try { 
     decodedValue = new String(Base64Utility.decode(parts[1])); 
    } catch (Base64Exception ex) { 
     requestContext.abortWith(createFaultResponse()); 
     return; 
    } 
    String[] namePassword = decodedValue.split(":"); 
    Employee emp = credentialService.getCredentialsByLoginAndPass(namePassword[0], namePassword[1], true); 
    if (emp != null) { 
    ResteasyProviderFactory.pushContext(Employee.class, emp); 
    } else { 
     throw new NullPointerException("False Login");//requestContext.abortWith(Response.status(401).build()); 
    } 

}

@Path("/people") 
public class PeopleRestService implements credentials { 
@Inject private PeopleService peopleService; 
@Inject private GenericUserRightsUtil genericUserRightsUtil; 


@Produces({ "application/json" }) 
@GET 
public Collection<Person> getPeople(@Context Employee emp) { 

    Employee emp = (Employee)crc.getProperty("Employee"); 

    return peopleService.getPeople(page, 5); 
} 

}

答えて

0

、あなたのリソースメソッドでリクエストを実行しているユーザーを識別するための簡単な方法をしたいです。要求のためPrincipalSecurityContextを設定したことがありますか?あなたのフィルタでは

、ユーザーの資格情報として有効な場合は、以下の

final SecurityContext currentSecurityContext = requestContext.getSecurityContext(); 
requestContext.setSecurityContext(new SecurityContext() { 

    @Override 
    public Principal getUserPrincipal() { 

     return new Principal() { 

      @Override 
      public String getName() { 
       return username; 
      } 
     }; 
    } 

    @Override 
    public boolean isUserInRole(String role) { 
     return true; 
    } 

    @Override 
    public boolean isSecure() { 
     return currentSecurityContext.isSecure(); 
    } 

    @Override 
    public String getAuthenticationScheme() { 
     return "Basic"; 
    } 
}); 

あなたのリソースメソッドは次のようになります:Principal、使用を取得するには

@GET 
@Path("{id}") 
@Produces(MediaType.APPLICATION_JSON) 
public Response foo(@PathParam("id") Long id, 
        @Context SecurityContext securityContext) { 
    ... 
} 

Principal principal = securityContext.getUserPrincipal(); 
String username = principal.getName(); 
関連する問題