Search in sources :

Example 36 with AuthenticationRequest

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

the class LogoutIntegrationTest method generateAuthRequest.

private AuthenticationRequest generateAuthRequest(Nonce nonce) {
    ResponseType responseType = new ResponseType(ResponseType.Value.CODE);
    State state = new State();
    Scope scope = new Scope();
    scope.add(OIDCScopeValue.OPENID);
    return new AuthenticationRequest.Builder(responseType, scope, new ClientID("test-client"), URI.create("http://localhost:8080/redirect")).state(state).nonce(nonce).build();
}
Also used : Scope(com.nimbusds.oauth2.sdk.Scope) State(com.nimbusds.oauth2.sdk.id.State) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

Example 37 with AuthenticationRequest

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

the class TokenIntegrationTest method generateAuthRequest.

private AuthenticationRequest generateAuthRequest(Scope scope, Optional<String> vtr, Optional<OIDCClaimsRequest> claimsRequest) {
    ResponseType responseType = new ResponseType(ResponseType.Value.CODE);
    State state = new State();
    Nonce nonce = new Nonce();
    AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(responseType, scope, new ClientID(CLIENT_ID), URI.create("http://localhost/redirect")).state(state).nonce(nonce);
    claimsRequest.ifPresent(builder::claims);
    vtr.ifPresent(v -> builder.customParameter("vtr", v));
    return builder.build();
}
Also used : Nonce(com.nimbusds.openid.connect.sdk.Nonce) State(com.nimbusds.oauth2.sdk.id.State) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

Example 38 with AuthenticationRequest

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

the class TokenHandler method tokenRequestHandler.

public APIGatewayProxyResponseEvent tokenRequestHandler(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());
        addAnnotation("grant_type", requestBody.get("grant_type"));
        String clientID;
        ClientRegistry client;
        try {
            clientID = tokenService.getClientIDFromPrivateKeyJWT(input.getBody()).orElseThrow();
            attachLogFieldToLogs(CLIENT_ID, clientID);
            addAnnotation("client_id", clientID);
            client = clientService.getClient(clientID).orElseThrow();
        } catch (NoSuchElementException e) {
            LOG.warn("Invalid client or client not found in Client Registry");
            return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_CLIENT.toJSONObject().toJSONString());
        }
        String baseUrl = configurationService.getOidcApiBaseURL().orElseThrow(() -> {
            LOG.error("Application was not configured with baseURL");
            return new RuntimeException("Application was not configured with baseURL");
        });
        String tokenUrl = buildURI(baseUrl, TOKEN_PATH).toString();
        Optional<ErrorObject> invalidPrivateKeyJwtError = segmentedFunctionCall("validatePrivateKeyJWT", () -> 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 segmentedFunctionCall("processRefreshTokenRequest", () -> processRefreshTokenRequest(requestBody, client.getScopes(), new RefreshToken(requestBody.get("refresh_token")), clientID));
        }
        AuthCodeExchangeData authCodeExchangeData;
        try {
            authCodeExchangeData = segmentedFunctionCall("authorisationCodeService", () -> 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());
        }
        updateAttachedLogFieldToLogs(CLIENT_SESSION_ID, authCodeExchangeData.getClientSessionId());
        ClientSession clientSession = authCodeExchangeData.getClientSession();
        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));
        }
        var authRequestRedirectURI = isDocCheckingAppUserWithSubjectId(clientSession) ? getRequestObjectClaim(authRequest, "redirect_uri", String.class) : authRequest.getRedirectionURI().toString();
        if (!authRequestRedirectURI.equals(requestBody.get("redirect_uri"))) {
            LOG.warn("Redirect URI for auth request ({}) does not match redirect URI for request body ({})", authRequestRedirectURI, requestBody.get("redirect_uri"));
            return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_GRANT.toJSONObject().toJSONString());
        }
        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 isConsentRequired = client.isConsentRequired() && !clientSession.getEffectiveVectorOfTrust().containsLevelOfConfidence();
        final OIDCClaimsRequest finalClaimsRequest = claimsRequest;
        OIDCTokenResponse tokenResponse;
        if (isDocCheckingAppUserWithSubjectId(clientSession)) {
            LOG.info("Doc Checking App User with SubjectId: true");
            Scope scope = new Scope(getRequestObjectScopeClaim(authRequest));
            tokenResponse = segmentedFunctionCall("generateTokenResponse", () -> tokenService.generateTokenResponse(clientID, clientSession.getDocAppSubjectId(), scope, additionalTokenClaims, clientSession.getDocAppSubjectId(), vot, null, false, finalClaimsRequest, true));
        } else {
            UserProfile userProfile = dynamoService.getUserProfileByEmail(authCodeExchangeData.getEmail());
            Subject subject = ClientSubjectHelper.getSubject(userProfile, client, dynamoService);
            tokenResponse = segmentedFunctionCall("generateTokenResponse", () -> tokenService.generateTokenResponse(clientID, new Subject(userProfile.getSubjectID()), authRequest.getScope(), additionalTokenClaims, subject, vot, userProfile.getClientConsent(), isConsentRequired, finalClaimsRequest, false));
        }
        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) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) 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) Scope(com.nimbusds.oauth2.sdk.Scope) 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 39 with AuthenticationRequest

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

the class AuthCodeHandlerTest method generateValidSessionAndAuthRequest.

private AuthenticationRequest generateValidSessionAndAuthRequest(CredentialTrustLevel requestedLevel, boolean docAppJourney) throws JOSEException {
    AuthenticationRequest authRequest;
    if (docAppJourney) {
        authRequest = generateRequestObjectAuthRequest();
    } else {
        ResponseType responseType = new ResponseType(ResponseType.Value.CODE);
        Scope scope = new Scope();
        Nonce nonce = new Nonce();
        scope.add(OIDCScopeValue.OPENID);
        authRequest = new AuthenticationRequest.Builder(responseType, scope, CLIENT_ID, REDIRECT_URI).state(new State()).nonce(nonce).build();
    }
    generateValidSession(authRequest.toParameters(), requestedLevel, docAppJourney);
    return authRequest;
}
Also used : Nonce(com.nimbusds.openid.connect.sdk.Nonce) Scope(com.nimbusds.oauth2.sdk.Scope) State(com.nimbusds.oauth2.sdk.id.State) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

Example 40 with AuthenticationRequest

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

the class AuthCodeHandlerTest method shouldGenerateSuccessfulAuthResponseAndUpliftAsNecessary.

@ParameterizedTest
@MethodSource("upliftTestParameters")
void shouldGenerateSuccessfulAuthResponseAndUpliftAsNecessary(CredentialTrustLevel initialLevel, CredentialTrustLevel requestedLevel, CredentialTrustLevel finalLevel, boolean docAppJourney) throws ClientNotFoundException, URISyntaxException, Json.JsonException, JOSEException {
    AuthorizationCode authorizationCode = new AuthorizationCode();
    AuthenticationRequest authRequest = generateValidSessionAndAuthRequest(requestedLevel, docAppJourney);
    session.setCurrentCredentialStrength(initialLevel).setNewAccount(NEW);
    AuthenticationSuccessResponse authSuccessResponse = new AuthenticationSuccessResponse(authRequest.getRedirectionURI(), authorizationCode, null, null, authRequest.getState(), null, authRequest.getResponseMode());
    when(authorizationService.isClientRedirectUriValid(eq(CLIENT_ID), eq(REDIRECT_URI))).thenReturn(true);
    when(authorisationCodeService.generateAuthorisationCode(CLIENT_SESSION_ID, EMAIL, clientSession)).thenReturn(authorizationCode);
    when(authorizationService.generateSuccessfulAuthResponse(any(AuthenticationRequest.class), any(AuthorizationCode.class), any(URI.class), any(State.class))).thenReturn(authSuccessResponse);
    APIGatewayProxyResponseEvent response = generateApiRequest();
    assertThat(response, hasStatus(200));
    AuthCodeResponse authCodeResponse = objectMapper.readValue(response.getBody(), AuthCodeResponse.class);
    assertThat(authCodeResponse.getLocation(), equalTo(authSuccessResponse.toURI().toString()));
    assertThat(session.getCurrentCredentialStrength(), equalTo(finalLevel));
    assertThat(session.isAuthenticated(), not(equalTo(docAppJourney)));
    verify(sessionService, times(docAppJourney ? 0 : 1)).save(session);
    verify(auditService).submitAuditEvent(OidcAuditableEvent.AUTH_CODE_ISSUED, "aws-session-id", SESSION_ID, CLIENT_ID.getValue(), AuditService.UNKNOWN, EMAIL, "123.123.123.123", AuditService.UNKNOWN, PERSISTENT_SESSION_ID);
    verify(cloudwatchMetricsService).incrementCounter("SignIn", Map.of("Account", "NEW", "Environment", "unit-test", "Client", CLIENT_ID.getValue()));
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) AuthCodeResponse(uk.gov.di.authentication.oidc.entity.AuthCodeResponse) State(com.nimbusds.oauth2.sdk.id.State) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) URI(java.net.URI) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

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