Search in sources :

Example 6 with ECKeyGenerator

use of com.nimbusds.jose.jwk.gen.ECKeyGenerator in project di-authentication-api by alphagov.

the class TokenHandlerTest method shouldReturn200ForSuccessfulTokenRequest.

@ParameterizedTest
@MethodSource("validVectorValues")
public void shouldReturn200ForSuccessfulTokenRequest(String vectorValue, boolean clientRegistryConsent, boolean expectedConsentRequired, boolean clientIdInHeader) throws JOSEException {
    KeyPair keyPair = generateRsaKeyPair();
    UserProfile userProfile = generateUserProfile();
    SignedJWT signedJWT = generateIDToken(CLIENT_ID, PUBLIC_SUBJECT, "issuer-url", new ECKeyGenerator(Curve.P_256).algorithm(JWSAlgorithm.ES256).generate());
    OIDCTokenResponse tokenResponse = new OIDCTokenResponse(new OIDCTokens(signedJWT, accessToken, refreshToken));
    PrivateKeyJWT privateKeyJWT = generatePrivateKeyJWT(keyPair.getPrivate());
    ClientRegistry clientRegistry = generateClientRegistry(keyPair, clientRegistryConsent);
    when(tokenService.validateTokenRequestParams(anyString())).thenReturn(Optional.empty());
    when(clientService.getClient(eq(CLIENT_ID))).thenReturn(Optional.of(clientRegistry));
    when(tokenService.getClientIDFromPrivateKeyJWT(anyString())).thenReturn(Optional.of(CLIENT_ID));
    when(tokenService.validatePrivateKeyJWT(anyString(), eq(clientRegistry.getPublicKey()), eq(BASE_URI), eq(CLIENT_ID))).thenReturn(Optional.empty());
    String authCode = new AuthorizationCode().toString();
    AuthenticationRequest authenticationRequest = generateAuthRequest(JsonArrayHelper.jsonArrayOf(vectorValue));
    VectorOfTrust vtr = VectorOfTrust.parseFromAuthRequestAttribute(authenticationRequest.getCustomParameter("vtr"));
    when(authorisationCodeService.getExchangeDataForCode(authCode)).thenReturn(Optional.of(new AuthCodeExchangeData().setEmail(TEST_EMAIL).setClientSessionId(CLIENT_SESSION_ID).setClientSession(new ClientSession(authenticationRequest.toParameters(), LocalDateTime.now(), vtr))));
    when(dynamoService.getUserProfileByEmail(eq(TEST_EMAIL))).thenReturn(userProfile);
    when(tokenService.generateTokenResponse(CLIENT_ID, INTERNAL_SUBJECT, SCOPES, Map.of("nonce", NONCE), PUBLIC_SUBJECT, vtr.retrieveVectorOfTrustForToken(), userProfile.getClientConsent(), expectedConsentRequired, null, false)).thenReturn(tokenResponse);
    APIGatewayProxyResponseEvent result = generateApiGatewayRequest(privateKeyJWT, authCode, CLIENT_ID, clientIdInHeader);
    assertThat(result, hasStatus(200));
    assertTrue(result.getBody().contains(refreshToken.getValue()));
    assertTrue(result.getBody().contains(accessToken.getValue()));
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) KeyPair(java.security.KeyPair) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) PrivateKeyJWT(com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT) ECKeyGenerator(com.nimbusds.jose.jwk.gen.ECKeyGenerator) VectorOfTrust(uk.gov.di.authentication.shared.entity.VectorOfTrust) RequestObjectTestHelper.generateSignedJWT(uk.gov.di.authentication.oidc.helper.RequestObjectTestHelper.generateSignedJWT) SignedJWT(com.nimbusds.jwt.SignedJWT) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) AuthCodeExchangeData(uk.gov.di.authentication.shared.entity.AuthCodeExchangeData) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 7 with ECKeyGenerator

use of com.nimbusds.jose.jwk.gen.ECKeyGenerator in project di-authentication-api by alphagov.

the class TokenHandlerTest method shouldReturn200ForSuccessfulDocAppJourneyTokenRequest.

@Test
void shouldReturn200ForSuccessfulDocAppJourneyTokenRequest() throws JOSEException {
    KeyPair keyPair = generateRsaKeyPair();
    UserProfile userProfile = generateUserProfile();
    SignedJWT signedJWT = generateIDToken(DOC_APP_CLIENT_ID.getValue(), PUBLIC_SUBJECT, "issuer-url", new ECKeyGenerator(Curve.P_256).algorithm(JWSAlgorithm.ES256).generate());
    OIDCTokenResponse tokenResponse = new OIDCTokenResponse(new OIDCTokens(signedJWT, accessToken, refreshToken));
    PrivateKeyJWT privateKeyJWT = generatePrivateKeyJWT(keyPair.getPrivate());
    ClientRegistry clientRegistry = generateClientRegistry(keyPair, false);
    when(tokenService.validateTokenRequestParams(anyString())).thenReturn(Optional.empty());
    when(clientService.getClient(DOC_APP_CLIENT_ID.getValue())).thenReturn(Optional.of(clientRegistry));
    when(tokenService.getClientIDFromPrivateKeyJWT(anyString())).thenReturn(Optional.of(DOC_APP_CLIENT_ID.getValue()));
    when(tokenService.validatePrivateKeyJWT(anyString(), eq(clientRegistry.getPublicKey()), eq(BASE_URI), eq(DOC_APP_CLIENT_ID.getValue()))).thenReturn(Optional.empty());
    String authCode = new AuthorizationCode().toString();
    AuthorizationRequest authenticationRequest = generateRequestObjectAuthRequest();
    VectorOfTrust vtr = VectorOfTrust.parseFromAuthRequestAttribute(authenticationRequest.getCustomParameter("vtr"));
    ClientSession clientSession = new ClientSession(authenticationRequest.toParameters(), LocalDateTime.now(), vtr);
    clientSession.setDocAppSubjectId(DOC_APP_USER_PUBLIC_SUBJECT);
    when(authorisationCodeService.getExchangeDataForCode(authCode)).thenReturn(Optional.of(new AuthCodeExchangeData().setEmail(TEST_EMAIL).setClientSessionId(CLIENT_SESSION_ID).setClientSession(clientSession)));
    when(dynamoService.getUserProfileByEmail(TEST_EMAIL)).thenReturn(userProfile);
    when(tokenService.generateTokenResponse(DOC_APP_CLIENT_ID.getValue(), DOC_APP_USER_PUBLIC_SUBJECT, new Scope(OIDCScopeValue.OPENID, DOC_CHECKING_APP), Map.of(), DOC_APP_USER_PUBLIC_SUBJECT, vtr.retrieveVectorOfTrustForToken(), null, false, null, true)).thenReturn(tokenResponse);
    APIGatewayProxyResponseEvent result = generateApiGatewayRequest(privateKeyJWT, authCode, DOC_APP_CLIENT_ID.getValue(), true);
    assertThat(result, hasStatus(200));
    assertTrue(result.getBody().contains(refreshToken.getValue()));
    assertTrue(result.getBody().contains(accessToken.getValue()));
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) KeyPair(java.security.KeyPair) AuthorizationRequest(com.nimbusds.oauth2.sdk.AuthorizationRequest) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) PrivateKeyJWT(com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT) ECKeyGenerator(com.nimbusds.jose.jwk.gen.ECKeyGenerator) VectorOfTrust(uk.gov.di.authentication.shared.entity.VectorOfTrust) RequestObjectTestHelper.generateSignedJWT(uk.gov.di.authentication.oidc.helper.RequestObjectTestHelper.generateSignedJWT) SignedJWT(com.nimbusds.jwt.SignedJWT) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) AuthCodeExchangeData(uk.gov.di.authentication.shared.entity.AuthCodeExchangeData) Scope(com.nimbusds.oauth2.sdk.Scope) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 8 with ECKeyGenerator

use of com.nimbusds.jose.jwk.gen.ECKeyGenerator in project di-authentication-api by alphagov.

the class SignedCredentialHelper method generateCredential.

public static SignedJWT generateCredential() {
    try {
        ECKey ecSigningKey = new ECKeyGenerator(Curve.P_256).algorithm(JWSAlgorithm.ES256).generate();
        JWSSigner signer = new ECDSASigner(ecSigningKey);
        JWSHeader jwsHeader = new JWSHeader.Builder(JWSAlgorithm.ES256).keyID(ecSigningKey.getKeyID()).build();
        var signedJWT = new SignedJWT(jwsHeader, new JWTClaimsSet.Builder().build());
        signedJWT.sign(signer);
        return signedJWT;
    } catch (JOSEException e) {
        throw new RuntimeException(e);
    }
}
Also used : ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) ECKeyGenerator(com.nimbusds.jose.jwk.gen.ECKeyGenerator) ECKey(com.nimbusds.jose.jwk.ECKey) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 9 with ECKeyGenerator

use of com.nimbusds.jose.jwk.gen.ECKeyGenerator in project di-authentication-api by alphagov.

the class DocAppCriServiceTest method signJWTWithKMS.

private void signJWTWithKMS() throws JOSEException {
    var ecSigningKey = new ECKeyGenerator(Curve.P_256).keyID(KEY_ID).algorithm(JWSAlgorithm.ES256).generate();
    var claimsSet = new JWTAuthenticationClaimsSet(new ClientID(CLIENT_ID), singletonList(new Audience(buildURI(CRI_URI.toString(), "token"))), NowHelper.nowPlus(5, ChronoUnit.MINUTES), null, NowHelper.now(), new JWTID());
    var ecdsaSigner = new ECDSASigner(ecSigningKey);
    var jwsHeader = new JWSHeader.Builder(JWSAlgorithm.ES256).keyID(ecSigningKey.getKeyID()).build();
    var signedJWT = new SignedJWT(jwsHeader, claimsSet.toJWTClaimsSet());
    unchecked(signedJWT::sign).accept(ecdsaSigner);
    var signResult = new SignResult();
    byte[] idTokenSignatureDer = ECDSA.transcodeSignatureToDER(signedJWT.getSignature().decode());
    signResult.setSignature(ByteBuffer.wrap(idTokenSignatureDer));
    signResult.setKeyId(KEY_ID);
    signResult.setSigningAlgorithm(JWSAlgorithm.ES256.getName());
    when(kmsService.sign(any(SignRequest.class))).thenReturn(signResult);
}
Also used : SignResult(com.amazonaws.services.kms.model.SignResult) SignRequest(com.amazonaws.services.kms.model.SignRequest) Audience(com.nimbusds.oauth2.sdk.id.Audience) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) ECKeyGenerator(com.nimbusds.jose.jwk.gen.ECKeyGenerator) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) JWTID(com.nimbusds.oauth2.sdk.id.JWTID) JWTAuthenticationClaimsSet(com.nimbusds.oauth2.sdk.auth.JWTAuthenticationClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT)

Example 10 with ECKeyGenerator

use of com.nimbusds.jose.jwk.gen.ECKeyGenerator in project di-authentication-api by alphagov.

the class DocAppAuthorizeHandlerTest method createEncryptedJWT.

private EncryptedJWT createEncryptedJWT() throws JOSEException, ParseException {
    var ecSigningKey = new ECKeyGenerator(Curve.P_256).keyID("key-id").algorithm(JWSAlgorithm.ES256).generate();
    var ecdsaSigner = new ECDSASigner(ecSigningKey);
    var jwtClaimsSet = new JWTClaimsSet.Builder().claim("redirect_uri", REDIRECT_URI).claim("response_type", ResponseType.CODE.toString()).claim("client_id", DOC_APP_CLIENT_ID).issuer(DOC_APP_CLIENT_ID).build();
    var jwsHeader = new JWSHeader(JWSAlgorithm.ES256);
    var signedJWT = new SignedJWT(jwsHeader, jwtClaimsSet);
    signedJWT.sign(ecdsaSigner);
    var rsaEncryptionKey = new RSAKeyGenerator(2048).keyID("encrytion-key-id").generate().toRSAPublicKey();
    var jweObject = new JWEObject(new JWEHeader.Builder(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A256GCM).contentType("JWT").build(), new Payload(signedJWT));
    jweObject.encrypt(new RSAEncrypter(rsaEncryptionKey));
    return EncryptedJWT.parse(jweObject.serialize());
}
Also used : ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) RSAEncrypter(com.nimbusds.jose.crypto.RSAEncrypter) ECKeyGenerator(com.nimbusds.jose.jwk.gen.ECKeyGenerator) RSAKeyGenerator(com.nimbusds.jose.jwk.gen.RSAKeyGenerator) SignedJWT(com.nimbusds.jwt.SignedJWT) JWEHeader(com.nimbusds.jose.JWEHeader) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) JWEObject(com.nimbusds.jose.JWEObject) Payload(com.nimbusds.jose.Payload) JWSHeader(com.nimbusds.jose.JWSHeader)

Aggregations

ECKeyGenerator (com.nimbusds.jose.jwk.gen.ECKeyGenerator)28 ECDSASigner (com.nimbusds.jose.crypto.ECDSASigner)18 SignedJWT (com.nimbusds.jwt.SignedJWT)17 ECKey (com.nimbusds.jose.jwk.ECKey)13 SignRequest (com.amazonaws.services.kms.model.SignRequest)6 SignResult (com.amazonaws.services.kms.model.SignResult)6 Test (org.junit.jupiter.api.Test)6 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)5 JOSEException (com.nimbusds.jose.JOSEException)5 JWSHeader (com.nimbusds.jose.JWSHeader)5 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)5 JWEObject (com.nimbusds.jose.JWEObject)4 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)4 JWSSigner (com.nimbusds.jose.JWSSigner)3 RSAKeyGenerator (com.nimbusds.jose.jwk.gen.RSAKeyGenerator)3 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)3 PrivateKeyJWT (com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT)3 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)3 OIDCTokens (com.nimbusds.openid.connect.sdk.token.OIDCTokens)3 KeyPair (java.security.KeyPair)3