Search in sources :

Example 21 with com.nimbusds.oauth2.sdk

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

the class TokenServiceTest method shouldOnlyIncludeIdentityClaimsInAccessTokenWhenRequested.

@Test
void shouldOnlyIncludeIdentityClaimsInAccessTokenWhenRequested() throws ParseException, JOSEException, Json.JsonException, com.nimbusds.oauth2.sdk.ParseException {
    var claimsSetRequest = new ClaimsSetRequest().add("nickname").add("birthdate");
    var oidcClaimsRequest = new OIDCClaimsRequest().withUserInfoClaimsRequest(claimsSetRequest);
    when(configurationService.getTokenSigningKeyAlias()).thenReturn(KEY_ID);
    createSignedIdToken();
    createSignedAccessToken();
    Map<String, Object> additionalTokenClaims = new HashMap<>();
    additionalTokenClaims.put("nonce", nonce);
    Set<String> claimsForListOfScopes = ValidScopes.getClaimsForListOfScopes(SCOPES_OFFLINE_ACCESS.toStringList());
    OIDCTokenResponse tokenResponse = tokenService.generateTokenResponse(CLIENT_ID, INTERNAL_SUBJECT, SCOPES_OFFLINE_ACCESS, additionalTokenClaims, PUBLIC_SUBJECT, VOT, Collections.singletonList(new ClientConsent(CLIENT_ID, claimsForListOfScopes, LocalDateTime.now(ZoneId.of("UTC")).toString())), false, oidcClaimsRequest, false);
    assertSuccessfullTokenResponse(tokenResponse);
    assertNotNull(tokenResponse.getOIDCTokens().getRefreshToken());
    assertNull(SignedJWT.parse(tokenResponse.getOIDCTokens().getRefreshToken().getValue()).getJWTClaimsSet().getClaim("claims"));
    JSONArray jsonarray = JSONArrayUtils.parse(SignedJWT.parse(tokenResponse.getOIDCTokens().getAccessToken().getValue()).getJWTClaimsSet().getClaim("claims").toString());
    assertTrue(jsonarray.contains("nickname"));
    assertTrue(jsonarray.contains("birthdate"));
    RefreshTokenStore refreshTokenStore = new RefreshTokenStore(tokenResponse.getOIDCTokens().getRefreshToken().getValue(), INTERNAL_SUBJECT.getValue());
    ArgumentCaptor<String> redisKey = ArgumentCaptor.forClass(String.class);
    verify(redisConnectionService).saveWithExpiry(redisKey.capture(), eq(objectMapper.writeValueAsString(refreshTokenStore)), eq(300L));
    var refreshToken = SignedJWT.parse(tokenResponse.getOIDCTokens().getRefreshToken().getValue());
    var jti = refreshToken.getJWTClaimsSet().getJWTID();
    assertThat(redisKey.getValue(), startsWith(REFRESH_TOKEN_PREFIX));
    assertThat(redisKey.getValue().split(":")[1], equalTo(jti));
}
Also used : ClaimsSetRequest(com.nimbusds.openid.connect.sdk.claims.ClaimsSetRequest) RefreshTokenStore(uk.gov.di.authentication.shared.entity.RefreshTokenStore) HashMap(java.util.HashMap) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) JSONArray(net.minidev.json.JSONArray) ClientConsent(uk.gov.di.authentication.shared.entity.ClientConsent) OIDCClaimsRequest(com.nimbusds.openid.connect.sdk.OIDCClaimsRequest) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) Test(org.junit.jupiter.api.Test)

Example 22 with com.nimbusds.oauth2.sdk

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

the class AccessTokenService method parse.

public AccessTokenInfo parse(String authorizationHeader, boolean identityEnabled) throws AccessTokenException {
    AccessToken accessToken;
    try {
        accessToken = AccessToken.parse(authorizationHeader, AccessTokenType.BEARER);
    } catch (com.nimbusds.oauth2.sdk.ParseException e) {
        LOG.warn("Unable to parse AccessToken");
        throw new AccessTokenException("Unable to parse AccessToken", BearerTokenError.INVALID_TOKEN);
    }
    SignedJWT signedJWT;
    try {
        signedJWT = SignedJWT.parse(accessToken.getValue());
        var currentDateTime = NowHelper.now();
        if (DateUtils.isBefore(signedJWT.getJWTClaimsSet().getExpirationTime(), currentDateTime, 0)) {
            LOG.warn("Access Token has expired. Access Token expires at: {}. CurrentDateTime is: {}", signedJWT.getJWTClaimsSet().getExpirationTime(), currentDateTime);
            throw new AccessTokenException(INVALID_ACCESS_TOKEN, BearerTokenError.INVALID_TOKEN);
        }
        if (!tokenValidationService.validateAccessTokenSignature(accessToken)) {
            LOG.warn("Unable to validate AccessToken signature");
            throw new AccessTokenException("Unable to validate AccessToken signature", BearerTokenError.INVALID_TOKEN);
        }
        var clientID = signedJWT.getJWTClaimsSet().getStringClaim("client_id");
        var client = clientService.getClient(clientID);
        attachLogFieldToLogs(CLIENT_ID, clientID);
        if (client.isEmpty()) {
            LOG.warn("Client not found");
            throw new AccessTokenException("Client not found", BearerTokenError.INVALID_TOKEN);
        }
        var scopes = JSONArrayUtils.parse(signedJWT.getJWTClaimsSet().getClaim("scope").toString()).stream().map(Objects::toString).collect(Collectors.toList());
        if (!areScopesValid(scopes) || !client.get().getScopes().containsAll(scopes)) {
            LOG.warn("Invalid Scopes: {}", scopes);
            throw new AccessTokenException("Invalid Scopes", OAuth2Error.INVALID_SCOPE);
        }
        List<String> identityClaims = null;
        if (identityEnabled) {
            identityClaims = getIdentityClaims(signedJWT.getJWTClaimsSet());
        }
        var subject = signedJWT.getJWTClaimsSet().getSubject();
        var accessTokenStore = getAccessTokenStore(clientID, subject);
        if (accessTokenStore.isEmpty()) {
            LOG.warn("Access Token Store is empty. Access Token expires at: {}. CurrentDateTime is: {}. JWTID in Access Token sent in request: {}", signedJWT.getJWTClaimsSet().getExpirationTime(), currentDateTime, signedJWT.getJWTClaimsSet().getJWTID());
            throw new AccessTokenException(INVALID_ACCESS_TOKEN, BearerTokenError.INVALID_TOKEN);
        }
        if (!accessTokenStore.get().getToken().equals(accessToken.getValue())) {
            LOG.warn("Access Token in Access Token Store is different to Access Token sent in request");
            var storeJwtId = SignedJWT.parse(accessTokenStore.get().getToken()).getJWTClaimsSet().getJWTID();
            LOG.warn("JWTID in AccessTokenStore: {} compared to JWTID in Access Token sent in request: {}", storeJwtId, signedJWT.getJWTClaimsSet().getJWTID());
            throw new AccessTokenException(INVALID_ACCESS_TOKEN, BearerTokenError.INVALID_TOKEN);
        }
        return new AccessTokenInfo(accessTokenStore.get(), subject, scopes, identityClaims);
    } catch (ParseException e) {
        LOG.warn("Unable to parse AccessToken to SignedJWT");
        throw new AccessTokenException("Unable to parse AccessToken to SignedJWT", BearerTokenError.INVALID_TOKEN);
    } catch (com.nimbusds.oauth2.sdk.ParseException e) {
        LOG.warn("Unable to parse ClaimSet in AccessToken");
        throw new AccessTokenException("Unable to parse ClaimSet in AccessToken", BearerTokenError.INVALID_TOKEN);
    }
}
Also used : AccessTokenInfo(uk.gov.di.authentication.oidc.entity.AccessTokenInfo) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) AccessTokenException(uk.gov.di.authentication.shared.exceptions.AccessTokenException) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException)

Aggregations

URI (java.net.URI)7 IOException (java.io.IOException)6 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)5 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)5 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)5 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)4 ParseException (com.nimbusds.oauth2.sdk.ParseException)4 AccessTokenResponse (com.nimbusds.oauth2.sdk.AccessTokenResponse)3 TokenRequest (com.nimbusds.oauth2.sdk.TokenRequest)3 TokenResponse (com.nimbusds.oauth2.sdk.TokenResponse)3 ClientSecretBasic (com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)3 Issuer (com.nimbusds.oauth2.sdk.id.Issuer)3 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)3 ParseException (java.text.ParseException)3 com.nimbusds.oauth2.sdk (com.nimbusds.oauth2.sdk)2 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)2 AuthorizationResponse (com.nimbusds.oauth2.sdk.AuthorizationResponse)2 AuthorizationSuccessResponse (com.nimbusds.oauth2.sdk.AuthorizationSuccessResponse)2 Secret (com.nimbusds.oauth2.sdk.auth.Secret)2 Audience (com.nimbusds.oauth2.sdk.id.Audience)2