View Javadoc

1   package com.atlassian.asap.core.client.http;
2   
3   import com.atlassian.asap.api.Jwt;
4   import com.atlassian.asap.api.client.http.AuthorizationHeaderGenerator;
5   import com.atlassian.asap.api.exception.CannotRetrieveKeyException;
6   import com.atlassian.asap.api.exception.InvalidTokenException;
7   import com.atlassian.asap.core.JwtConstants;
8   import com.atlassian.asap.core.keys.KeyProvider;
9   import com.atlassian.asap.core.keys.privatekey.PrivateKeyProviderFactory;
10  import com.atlassian.asap.core.serializer.JwtSerializer;
11  import com.atlassian.asap.core.validator.ValidatedKeyId;
12  import com.atlassian.asap.nimbus.serializer.NimbusJwtSerializer;
13  
14  import java.net.URI;
15  import java.security.PrivateKey;
16  import java.util.Objects;
17  
18  public class AuthorizationHeaderGeneratorImpl implements AuthorizationHeaderGenerator {
19      private final JwtSerializer jwtSerializer;
20      private final KeyProvider<PrivateKey> privateKeyProvider;
21  
22      /**
23       * Creates a new instance of {@link AuthorizationHeaderGeneratorImpl}.
24       *
25       * @param jwtSerializer      the serializer to use for signing and serializing a JWT object
26       * @param privateKeyProvider the key provider to use for retrieving private keys used in signing
27       */
28      public AuthorizationHeaderGeneratorImpl(JwtSerializer jwtSerializer, KeyProvider<PrivateKey> privateKeyProvider) {
29          this.jwtSerializer = Objects.requireNonNull(jwtSerializer);
30          this.privateKeyProvider = Objects.requireNonNull(privateKeyProvider);
31      }
32  
33      /**
34       * Constructs a default instance for the given private key path.
35       *
36       * @param privateKeyPath location of the private keys
37       * @return a new instance of the header generator
38       */
39      public static AuthorizationHeaderGenerator createDefault(URI privateKeyPath) {
40          KeyProvider<PrivateKey> keyProvider = PrivateKeyProviderFactory.createPrivateKeyProvider(privateKeyPath);
41          return new AuthorizationHeaderGeneratorImpl(new NimbusJwtSerializer(), keyProvider);
42      }
43  
44      @Override
45      public String generateAuthorizationHeader(Jwt jwt) throws InvalidTokenException, CannotRetrieveKeyException {
46          ValidatedKeyId validatedKeyId = ValidatedKeyId.validate(jwt.getHeader().getKeyId());
47  
48          PrivateKey privateKey = privateKeyProvider.getKey(validatedKeyId);
49  
50          return JwtConstants.HTTP_AUTHORIZATION_HEADER_VALUE_PREFIX + jwtSerializer.serialize(jwt, privateKey);
51      }
52  }