Search in sources :

Example 56 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.

the class TokenHandler method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        LOG.info("Token request received");
        Optional<ErrorObject> invalidRequestParamError = tokenService.validateTokenRequestParams(input.getBody());
        if (invalidRequestParamError.isPresent()) {
            LOG.warn("Invalid Token Request. ErrorCode: {}. ErrorDescription: {}", invalidRequestParamError.get().getCode(), invalidRequestParamError.get().getDescription());
            return generateApiGatewayProxyResponse(400, invalidRequestParamError.get().toJSONObject().toJSONString());
        }
        Map<String, String> requestBody = parseRequestBody(input.getBody());
        String clientID = requestBody.get("client_id");
        ClientRegistry client;
        try {
            client = clientService.getClient(clientID).orElseThrow();
        } catch (NoSuchElementException e) {
            LOG.warn("Client not found in Client Registry with Client ID {}", clientID);
            return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_CLIENT.toJSONObject().toJSONString());
        }
        String baseUrl = configurationService.getBaseURL().orElseThrow(() -> {
            LOG.error("Application was not configured with baseURL");
            // exceptions
            return new RuntimeException("Application was not configured with baseURL");
        });
        String tokenUrl = buildURI(baseUrl, TOKEN_PATH).toString();
        Optional<ErrorObject> invalidPrivateKeyJwtError = tokenService.validatePrivateKeyJWT(input.getBody(), client.getPublicKey(), tokenUrl, clientID);
        if (invalidPrivateKeyJwtError.isPresent()) {
            LOG.warn("Private Key JWT is not valid for Client ID: {}", clientID);
            return generateApiGatewayProxyResponse(400, invalidPrivateKeyJwtError.get().toJSONObject().toJSONString());
        }
        if (requestBody.get("grant_type").equals(GrantType.REFRESH_TOKEN.getValue())) {
            LOG.info("Processing refresh token request");
            return processRefreshTokenRequest(requestBody, client.getScopes(), new RefreshToken(requestBody.get("refresh_token")));
        }
        AuthCodeExchangeData authCodeExchangeData;
        try {
            authCodeExchangeData = authorisationCodeService.getExchangeDataForCode(requestBody.get("code")).orElseThrow();
        } catch (NoSuchElementException e) {
            LOG.warn("Could not retrieve client session ID from code", e);
            return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_GRANT.toJSONObject().toJSONString());
        }
        ClientSession clientSession = clientSessionService.getClientSession(authCodeExchangeData.getClientSessionId());
        AuthenticationRequest authRequest;
        try {
            authRequest = AuthenticationRequest.parse(clientSession.getAuthRequestParams());
        } catch (ParseException e) {
            LOG.warn("Could not parse authentication request from client session", e);
            throw new RuntimeException(format("Unable to parse Auth Request\n Auth Request Params: %s \n Exception: %s", clientSession.getAuthRequestParams(), e));
        }
        if (!authRequest.getRedirectionURI().toString().equals(requestBody.get("redirect_uri"))) {
            LOG.warn("Redirect URI for auth request ({}) does not match redirect URI for request body ({})", authRequest.getRedirectionURI(), requestBody.get("redirect_uri"));
            return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_GRANT.toJSONObject().toJSONString());
        }
        UserProfile userProfile = dynamoService.getUserProfileByEmail(authCodeExchangeData.getEmail());
        Subject publicSubject = ClientSubjectHelper.getSubject(userProfile, client, dynamoService);
        Map<String, Object> additionalTokenClaims = new HashMap<>();
        if (authRequest.getNonce() != null) {
            additionalTokenClaims.put("nonce", authRequest.getNonce());
        }
        String vot = clientSession.getEffectiveVectorOfTrust().retrieveVectorOfTrustForToken();
        OIDCClaimsRequest claimsRequest = null;
        if (Objects.nonNull(clientSession.getEffectiveVectorOfTrust().getLevelOfConfidence()) && Objects.nonNull(authRequest.getOIDCClaims())) {
            claimsRequest = authRequest.getOIDCClaims();
        }
        var tokenResponse = tokenService.generateTokenResponse(clientID, new Subject(userProfile.getSubjectID()), authRequest.getScope(), additionalTokenClaims, publicSubject, vot, userProfile.getClientConsent(), client.isConsentRequired(), claimsRequest);
        clientSessionService.saveClientSession(authCodeExchangeData.getClientSessionId(), clientSession.setIdTokenHint(tokenResponse.getOIDCTokens().getIDToken().serialize()));
        LOG.info("Successfully generated tokens");
        return generateApiGatewayProxyResponse(200, tokenResponse.toJSONObject().toJSONString());
    });
}
Also used : UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) HashMap(java.util.HashMap) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) Subject(com.nimbusds.oauth2.sdk.id.Subject) AuthCodeExchangeData(uk.gov.di.authentication.shared.entity.AuthCodeExchangeData) OIDCClaimsRequest(com.nimbusds.openid.connect.sdk.OIDCClaimsRequest) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) ParseException(com.nimbusds.oauth2.sdk.ParseException) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) NoSuchElementException(java.util.NoSuchElementException)

Example 57 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.

the class AuthorizationServiceTest method shouldReturnErrorWhenInvalidVtrAttributeIsSentInRequest.

@Test
void shouldReturnErrorWhenInvalidVtrAttributeIsSentInRequest() {
    Scope scope = new Scope();
    scope.add(OIDCScopeValue.OPENID);
    when(dynamoClientService.getClient(CLIENT_ID.toString())).thenReturn(Optional.of(generateClientRegistry(REDIRECT_URI.toString(), CLIENT_ID.toString())));
    ResponseType responseType = new ResponseType(ResponseType.Value.CODE);
    AuthenticationRequest authRequest = generateAuthRequest(REDIRECT_URI.toString(), responseType, scope, jsonArrayOf("Cm.Cl.P1", "P1.Cl"), Optional.empty());
    Optional<ErrorObject> errorObject = authorizationService.validateAuthRequest(authRequest);
    assertThat(errorObject.get(), equalTo(new ErrorObject(OAuth2Error.INVALID_REQUEST_CODE, "Request vtr not valid")));
}
Also used : Scope(com.nimbusds.oauth2.sdk.Scope) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ResponseType(com.nimbusds.oauth2.sdk.ResponseType) Test(org.junit.jupiter.api.Test)

Example 58 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.

the class AuthorizationServiceTest method shouldReturnErrorWhenValidatingAuthRequestWhichContainsInvalidClaims.

@Test
void shouldReturnErrorWhenValidatingAuthRequestWhichContainsInvalidClaims() {
    ResponseType responseType = new ResponseType(ResponseType.Value.CODE);
    Scope scope = new Scope();
    scope.add(OIDCScopeValue.OPENID);
    when(dynamoClientService.getClient(CLIENT_ID.toString())).thenReturn(Optional.of(generateClientRegistry(REDIRECT_URI.toString(), CLIENT_ID.toString())));
    var claimsSetRequest = new ClaimsSetRequest().add("nickname").add("birthdate");
    var oidcClaimsRequest = new OIDCClaimsRequest().withUserInfoClaimsRequest(claimsSetRequest);
    AuthenticationRequest authRequest = generateAuthRequest(REDIRECT_URI.toString(), responseType, scope, jsonArrayOf("Cl.Cm", "Cl"), Optional.of(oidcClaimsRequest));
    Optional<ErrorObject> errorObject = authorizationService.validateAuthRequest(authRequest);
    assertThat(errorObject, equalTo(Optional.of(new ErrorObject(OAuth2Error.INVALID_REQUEST_CODE, "Request contains invalid claims"))));
}
Also used : ClaimsSetRequest(com.nimbusds.openid.connect.sdk.claims.ClaimsSetRequest) OIDCClaimsRequest(com.nimbusds.openid.connect.sdk.OIDCClaimsRequest) Scope(com.nimbusds.oauth2.sdk.Scope) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ResponseType(com.nimbusds.oauth2.sdk.ResponseType) Test(org.junit.jupiter.api.Test)

Example 59 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.

the class AuthorizationServiceTest method shouldSuccessfullyValidateAuthRequestWhenValidClaimsArePresent.

@Test
void shouldSuccessfullyValidateAuthRequestWhenValidClaimsArePresent() {
    ResponseType responseType = new ResponseType(ResponseType.Value.CODE);
    Scope scope = new Scope();
    scope.add(OIDCScopeValue.OPENID);
    when(dynamoClientService.getClient(CLIENT_ID.toString())).thenReturn(Optional.of(generateClientRegistry(REDIRECT_URI.toString(), CLIENT_ID.toString())));
    var claimsSetRequest = new ClaimsSetRequest().add("name").add("birthdate");
    var oidcClaimsRequest = new OIDCClaimsRequest().withUserInfoClaimsRequest(claimsSetRequest);
    AuthenticationRequest authRequest = generateAuthRequest(REDIRECT_URI.toString(), responseType, scope, jsonArrayOf("Cl.Cm", "Cl"), Optional.of(oidcClaimsRequest));
    Optional<ErrorObject> errorObject = authorizationService.validateAuthRequest(authRequest);
    assertThat(errorObject, equalTo(Optional.empty()));
}
Also used : ClaimsSetRequest(com.nimbusds.openid.connect.sdk.claims.ClaimsSetRequest) OIDCClaimsRequest(com.nimbusds.openid.connect.sdk.OIDCClaimsRequest) Scope(com.nimbusds.oauth2.sdk.Scope) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ResponseType(com.nimbusds.oauth2.sdk.ResponseType) Test(org.junit.jupiter.api.Test)

Example 60 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.

the class AuthorizationServiceTest method shouldGenerateSuccessfulAuthResponse.

@Test
void shouldGenerateSuccessfulAuthResponse() {
    AuthorizationCode authCode = new AuthorizationCode();
    Scope scope = new Scope();
    scope.add(OIDCScopeValue.OPENID);
    ResponseType responseType = new ResponseType(ResponseType.Value.CODE);
    AuthenticationRequest authRequest = generateAuthRequest(REDIRECT_URI.toString(), responseType, scope);
    AuthenticationSuccessResponse authSuccessResponse = authorizationService.generateSuccessfulAuthResponse(authRequest, authCode, REDIRECT_URI, STATE);
    assertThat(authSuccessResponse.getState(), equalTo(STATE));
    assertThat(authSuccessResponse.getAuthorizationCode(), equalTo(authCode));
    assertThat(authSuccessResponse.getRedirectionURI(), equalTo(REDIRECT_URI));
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) Scope(com.nimbusds.oauth2.sdk.Scope) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse) ResponseType(com.nimbusds.oauth2.sdk.ResponseType) Test(org.junit.jupiter.api.Test)

Aggregations

AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)73 Scope (com.nimbusds.oauth2.sdk.Scope)44 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)34 State (com.nimbusds.oauth2.sdk.id.State)29 Nonce (com.nimbusds.openid.connect.sdk.Nonce)27 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)24 Test (org.junit.jupiter.api.Test)19 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)16 URI (java.net.URI)16 ParseException (com.nimbusds.oauth2.sdk.ParseException)12 ClientSession (uk.gov.di.authentication.shared.entity.ClientSession)12 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)11 VectorOfTrust (uk.gov.di.authentication.shared.entity.VectorOfTrust)10 AuthenticationSuccessResponse (com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse)8 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)7 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)7 MethodSource (org.junit.jupiter.params.provider.MethodSource)6 SignedJWT (com.nimbusds.jwt.SignedJWT)5 OIDCClaimsRequest (com.nimbusds.openid.connect.sdk.OIDCClaimsRequest)5 HashMap (java.util.HashMap)5