View Javadoc

1   package com.atlassian.asap.core.server.jersey;
2   
3   import com.atlassian.asap.api.Jwt;
4   import com.atlassian.asap.api.exception.AuthenticationFailedException;
5   import com.atlassian.asap.api.exception.AuthorizationFailedException;
6   import com.atlassian.asap.api.server.http.RequestAuthenticator;
7   import com.sun.jersey.api.container.MappableContainerException;
8   import com.sun.jersey.api.core.HttpContext;
9   import com.sun.jersey.api.core.HttpRequestContext;
10  import com.sun.jersey.server.impl.inject.AbstractHttpContextInjectable;
11  
12  import javax.ws.rs.core.HttpHeaders;
13  import java.util.Objects;
14  
15  public class JwtInjectable extends AbstractHttpContextInjectable<Jwt> {
16      private final RequestAuthenticator requestAuthenticator;
17      private final JerseyRequestAuthorizer jerseyRequestAuthorizer;
18  
19      public JwtInjectable(RequestAuthenticator requestAuthenticator,
20                           JerseyRequestAuthorizer jerseyRequestAuthorizer) {
21          this.requestAuthenticator = Objects.requireNonNull(requestAuthenticator);
22          this.jerseyRequestAuthorizer = Objects.requireNonNull(jerseyRequestAuthorizer);
23      }
24  
25      @Override
26      public Jwt getValue(HttpContext httpContext) {
27          HttpRequestContext requestContext = httpContext.getRequest();
28          String authorizationHeader = requestContext.getHeaderValue(HttpHeaders.AUTHORIZATION);
29  
30          try {
31              // authenticate
32              Jwt authenticJwt = requestAuthenticator.authenticateRequest(authorizationHeader);
33  
34              // authorize
35              jerseyRequestAuthorizer.authorize(authenticJwt, requestContext);
36  
37              return authenticJwt;
38          } catch (AuthenticationFailedException | AuthorizationFailedException e) {
39              throw wrapException(e);
40          }
41      }
42  
43      private RuntimeException wrapException(Exception e) {
44          // Non-jersey exceptions have to wrapped in a MappableContainerException if you want them to be handled
45          // by a custom ExceptionMapper.
46          // http://jersey.java.net/nonav/apidocs/1.12/jersey/com/sun/jersey/api/container/ContainerException.html
47          return new MappableContainerException(e);
48      }
49  
50      public RequestAuthenticator getRequestAuthenticator() {
51          return this.requestAuthenticator;
52      }
53  
54      public JerseyRequestAuthorizer getJerseyRequestAuthorizer() {
55          return jerseyRequestAuthorizer;
56      }
57  }