Search in sources :

Example 66 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class TokenGeneratorHelper method generateIDToken.

public static SignedJWT generateIDToken(String clientId, Subject subject, String issuerUrl, JWK signingKey, Date expiryDate) {
    IDTokenClaimsSet idTokenClaims = new IDTokenClaimsSet(new Issuer(issuerUrl), subject, List.of(new Audience(clientId)), expiryDate, new Date());
    try {
        JWSSigner signer;
        JWSHeader.Builder jwsHeaderBuilder;
        if (signingKey instanceof RSAKey) {
            signer = new RSASSASigner(signingKey.toRSAKey());
            jwsHeaderBuilder = new JWSHeader.Builder(JWSAlgorithm.RS512);
        } else if (signingKey instanceof ECKey) {
            signer = new ECDSASigner(signingKey.toECKey());
            jwsHeaderBuilder = new JWSHeader.Builder(JWSAlgorithm.ES256);
        } else {
            throw new RuntimeException("Invalid JWKKey");
        }
        var signedJWT = new SignedJWT(jwsHeaderBuilder.keyID(signingKey.getKeyID()).build(), idTokenClaims.toJWTClaimsSet());
        signedJWT.sign(signer);
        return signedJWT;
    } catch (JOSEException | ParseException e) {
        throw new RuntimeException(e);
    }
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) Issuer(com.nimbusds.oauth2.sdk.id.Issuer) Audience(com.nimbusds.oauth2.sdk.id.Audience) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) ECKey(com.nimbusds.jose.jwk.ECKey) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) Date(java.util.Date) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) ParseException(com.nimbusds.oauth2.sdk.ParseException) JWSSigner(com.nimbusds.jose.JWSSigner) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 67 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class TokenService method generateRefreshTokenResponse.

public OIDCTokenResponse generateRefreshTokenResponse(String clientID, Subject internalSubject, List<String> scopes, Subject subject) {
    AccessToken accessToken = generateAndStoreAccessToken(clientID, internalSubject, scopes, subject, null);
    RefreshToken refreshToken = generateAndStoreRefreshToken(clientID, internalSubject, scopes, subject);
    return new OIDCTokenResponse(new OIDCTokens(accessToken, refreshToken));
}
Also used : RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens)

Example 68 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class TokenService method generateIDToken.

private SignedJWT generateIDToken(String clientId, Subject subject, Map<String, Object> additionalTokenClaims, AccessTokenHash accessTokenHash, String vot, boolean isDocAppJourney) {
    LOG.info("Generating IdToken");
    URI trustMarkUri = buildURI(configService.getOidcApiBaseURL().get(), "/trustmark");
    Date expiryDate = NowHelper.nowPlus(configService.getIDTokenExpiry(), ChronoUnit.SECONDS);
    IDTokenClaimsSet idTokenClaims = new IDTokenClaimsSet(new Issuer(configService.getOidcApiBaseURL().get()), subject, List.of(new Audience(clientId)), expiryDate, NowHelper.now());
    idTokenClaims.setAccessTokenHash(accessTokenHash);
    idTokenClaims.putAll(additionalTokenClaims);
    if (!isDocAppJourney) {
        idTokenClaims.setClaim("vot", vot);
    }
    idTokenClaims.setClaim("vtm", trustMarkUri.toString());
    try {
        return generateSignedJWT(idTokenClaims.toJWTClaimsSet(), Optional.empty());
    } catch (com.nimbusds.oauth2.sdk.ParseException e) {
        LOG.error("Error when trying to parse IDTokenClaims to JWTClaimSet", e);
        throw new RuntimeException(e);
    }
}
Also used : Issuer(com.nimbusds.oauth2.sdk.id.Issuer) Audience(com.nimbusds.oauth2.sdk.id.Audience) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) ParseException(com.nimbusds.oauth2.sdk.ParseException) URI(java.net.URI) ConstructUriHelper.buildURI(uk.gov.di.authentication.shared.helpers.ConstructUriHelper.buildURI) Date(java.util.Date)

Example 69 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class TokenService method generateAndStoreAccessToken.

private AccessToken generateAndStoreAccessToken(String clientId, Subject internalSubject, List<String> scopes, Subject subject, OIDCClaimsRequest claimsRequest) {
    LOG.info("Generating AccessToken");
    Date expiryDate = NowHelper.nowPlus(configService.getAccessTokenExpiry(), ChronoUnit.SECONDS);
    var jwtID = UUID.randomUUID().toString();
    LOG.info("AccessToken being created with JWTID: {}", jwtID);
    JWTClaimsSet.Builder claimSetBuilder = new JWTClaimsSet.Builder().claim("scope", scopes).issuer(configService.getOidcApiBaseURL().get()).expirationTime(expiryDate).issueTime(NowHelper.now()).claim("client_id", clientId).subject(subject.getValue()).jwtID(jwtID);
    if (Objects.nonNull(claimsRequest)) {
        claimSetBuilder.claim("claims", claimsRequest.getUserInfoClaimsRequest().getEntries().stream().map(ClaimsSetRequest.Entry::getClaimName).collect(Collectors.toList()));
    }
    SignedJWT signedJWT = generateSignedJWT(claimSetBuilder.build(), Optional.empty());
    AccessToken accessToken = new BearerAccessToken(signedJWT.serialize());
    try {
        redisConnectionService.saveWithExpiry(ACCESS_TOKEN_PREFIX + clientId + "." + subject.getValue(), objectMapper.writeValueAsString(new AccessTokenStore(accessToken.getValue(), internalSubject.getValue())), configService.getAccessTokenExpiry());
    } catch (JsonException e) {
        LOG.error("Unable to save access token to Redis");
        throw new RuntimeException(e);
    }
    return accessToken;
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) AccessTokenStore(uk.gov.di.authentication.shared.entity.AccessTokenStore) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) SignedJWT(com.nimbusds.jwt.SignedJWT) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Date(java.util.Date)

Example 70 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class LoginHandlerTest method shouldReturn200IfMigratedUserHasBeenProcessesSuccessfully.

@Test
void shouldReturn200IfMigratedUserHasBeenProcessesSuccessfully() throws JsonProcessingException, Json.JsonException {
    when(configurationService.getTermsAndConditionsVersion()).thenReturn("1.0");
    String legacySubjectId = new Subject().getValue();
    UserProfile userProfile = generateUserProfile(legacySubjectId);
    when(authenticationService.getUserProfileByEmailMaybe(EMAIL)).thenReturn(Optional.of(userProfile));
    userCredentials.setPassword(null);
    when(userMigrationService.processMigratedUser(userCredentials, PASSWORD)).thenReturn(true);
    when(clientSession.getAuthRequestParams()).thenReturn(generateAuthRequest().toParameters());
    usingValidSession();
    APIGatewayProxyRequestEvent event = new APIGatewayProxyRequestEvent();
    event.setHeaders(Map.of("Session-Id", session.getSessionId()));
    event.setBody(format("{ \"password\": \"%s\", \"email\": \"%s\" }", PASSWORD, EMAIL));
    APIGatewayProxyResponseEvent result = handler.handleRequest(event, context);
    assertThat(result, hasStatus(200));
    LoginResponse response = objectMapper.readValue(result.getBody(), LoginResponse.class);
    assertThat(response.getLatestTermsAndConditionsAccepted(), equalTo(true));
    assertThat(response.getRedactedPhoneNumber(), equalTo(RedactPhoneNumberHelper.redactPhoneNumber(PHONE_NUMBER)));
    verify(sessionService).save(argThat(session -> session.isNewAccount() == Session.AccountState.EXISTING));
}
Also used : ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) BeforeEach(org.junit.jupiter.api.BeforeEach) Json(uk.gov.di.authentication.shared.serialization.Json) CodeStorageService(uk.gov.di.authentication.shared.services.CodeStorageService) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) Date(java.util.Date) Matchers.not(org.hamcrest.Matchers.not) Context(com.amazonaws.services.lambda.runtime.Context) Session(uk.gov.di.authentication.shared.entity.Session) ResponseType(com.nimbusds.oauth2.sdk.ResponseType) LogEventMatcher.withMessageContaining(uk.gov.di.authentication.sharedtest.logging.LogEventMatcher.withMessageContaining) Map(java.util.Map) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) URI(java.net.URI) FrontendAuditableEvent(uk.gov.di.authentication.frontendapi.domain.FrontendAuditableEvent) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) AuditService(uk.gov.di.authentication.shared.services.AuditService) OIDCScopeValue(com.nimbusds.openid.connect.sdk.OIDCScopeValue) APIGatewayProxyResponseEventMatcher.hasJsonBody(uk.gov.di.authentication.sharedtest.matchers.APIGatewayProxyResponseEventMatcher.hasJsonBody) ZoneId(java.time.ZoneId) String.format(java.lang.String.format) ClientSessionService(uk.gov.di.authentication.shared.services.ClientSessionService) Test(org.junit.jupiter.api.Test) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) Matchers.equalTo(org.hamcrest.Matchers.equalTo) SerializationService(uk.gov.di.authentication.shared.services.SerializationService) Optional(java.util.Optional) Nonce(com.nimbusds.openid.connect.sdk.Nonce) UserCredentials(uk.gov.di.authentication.shared.entity.UserCredentials) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) IdGenerator(uk.gov.di.authentication.shared.helpers.IdGenerator) UserMigrationService(uk.gov.di.authentication.frontendapi.services.UserMigrationService) SessionService(uk.gov.di.authentication.shared.services.SessionService) LocalDateTime(java.time.LocalDateTime) ConfigurationService(uk.gov.di.authentication.shared.services.ConfigurationService) HashMap(java.util.HashMap) ArgumentMatchers.anyMap(org.mockito.ArgumentMatchers.anyMap) AuthenticationService(uk.gov.di.authentication.shared.services.AuthenticationService) RequestEventHelper.contextWithSourceIp(uk.gov.di.authentication.sharedtest.helper.RequestEventHelper.contextWithSourceIp) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) ClientService(uk.gov.di.authentication.shared.services.ClientService) Subject(com.nimbusds.oauth2.sdk.id.Subject) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) LoginResponse(uk.gov.di.authentication.frontendapi.entity.LoginResponse) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) Scope(com.nimbusds.oauth2.sdk.Scope) State(com.nimbusds.oauth2.sdk.id.State) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Mockito.when(org.mockito.Mockito.when) RedactPhoneNumberHelper(uk.gov.di.authentication.frontendapi.helpers.RedactPhoneNumberHelper) VectorOfTrust(uk.gov.di.authentication.shared.entity.VectorOfTrust) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) Mockito.verify(org.mockito.Mockito.verify) AfterEach(org.junit.jupiter.api.AfterEach) CaptureLoggingExtension(uk.gov.di.authentication.sharedtest.logging.CaptureLoggingExtension) Matchers.hasItem(org.hamcrest.Matchers.hasItem) APIGatewayProxyResponseEventMatcher.hasStatus(uk.gov.di.authentication.sharedtest.matchers.APIGatewayProxyResponseEventMatcher.hasStatus) PersistentIdHelper(uk.gov.di.authentication.shared.helpers.PersistentIdHelper) Collections(java.util.Collections) TermsAndConditions(uk.gov.di.authentication.shared.entity.TermsAndConditions) JsonArrayHelper.jsonArrayOf(uk.gov.di.authentication.sharedtest.helper.JsonArrayHelper.jsonArrayOf) LoginResponse(uk.gov.di.authentication.frontendapi.entity.LoginResponse) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) Subject(com.nimbusds.oauth2.sdk.id.Subject) Test(org.junit.jupiter.api.Test)

Aggregations

Subject (com.nimbusds.oauth2.sdk.id.Subject)59 Test (org.junit.jupiter.api.Test)36 SignedJWT (com.nimbusds.jwt.SignedJWT)22 Date (java.util.Date)22 ApiGatewayHandlerIntegrationTest (uk.gov.di.authentication.sharedtest.basetest.ApiGatewayHandlerIntegrationTest)19 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)18 KeyPair (java.security.KeyPair)16 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)15 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)13 ParseException (com.nimbusds.oauth2.sdk.ParseException)12 Scope (com.nimbusds.oauth2.sdk.Scope)12 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)11 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)11 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)10 ECKeyGenerator (com.nimbusds.jose.jwk.gen.ECKeyGenerator)9 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)9 ECDSASigner (com.nimbusds.jose.crypto.ECDSASigner)8 Issuer (com.nimbusds.oauth2.sdk.id.Issuer)8 IDTokenClaimsSet (com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet)8 LocalDateTime (java.time.LocalDateTime)8