Search in sources :

Example 11 with AuthenticationRequest

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

the class AuthCodeHandler method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        Session session = sessionService.getSessionFromRequestHeaders(input.getHeaders()).orElse(null);
        if (Objects.isNull(session)) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1000);
        }
        String clientSessionId = getHeaderValueFromHeaders(input.getHeaders(), CLIENT_SESSION_ID_HEADER, configurationService.getHeadersCaseInsensitive());
        if (Objects.isNull(clientSessionId)) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1018);
        }
        attachSessionIdToLogs(session);
        attachLogFieldToLogs(CLIENT_SESSION_ID, clientSessionId);
        LOG.info("Processing request");
        AuthenticationRequest authenticationRequest;
        ClientSession clientSession;
        try {
            clientSession = clientSessionService.getClientSessionFromRequestHeaders(input.getHeaders()).orElse(null);
            if (Objects.isNull(clientSession)) {
                LOG.info("ClientSession not found");
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1018);
            }
            authenticationRequest = AuthenticationRequest.parse(clientSession.getAuthRequestParams());
        } catch (ParseException e) {
            if (e.getRedirectionURI() == null) {
                LOG.warn("Authentication request could not be parsed: redirect URI or Client ID is missing from auth request", e);
                throw new RuntimeException("Redirect URI or Client ID is missing from auth request", e);
            }
            AuthenticationErrorResponse errorResponse = authorizationService.generateAuthenticationErrorResponse(e.getRedirectionURI(), e.getState(), e.getResponseMode(), e.getErrorObject());
            LOG.warn("Authentication request could not be parsed", e);
            return generateResponse(new AuthCodeResponse(errorResponse.toURI().toString()));
        }
        try {
            if (!authorizationService.isClientRedirectUriValid(authenticationRequest.getClientID(), authenticationRequest.getRedirectionURI())) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1016);
            }
            VectorOfTrust requestedVectorOfTrust = clientSession.getEffectiveVectorOfTrust();
            if (isNull(session.getCurrentCredentialStrength()) || requestedVectorOfTrust.getCredentialTrustLevel().compareTo(session.getCurrentCredentialStrength()) > 0) {
                session.setCurrentCredentialStrength(requestedVectorOfTrust.getCredentialTrustLevel());
            }
            AuthorizationCode authCode = authorisationCodeService.generateAuthorisationCode(clientSessionId, session.getEmailAddress());
            AuthenticationSuccessResponse authenticationResponse = authorizationService.generateSuccessfulAuthResponse(authenticationRequest, authCode);
            LOG.info("Successfully processed request");
            cloudwatchMetricsService.incrementCounter("SignIn", Map.of("Account", session.isNewAccount().name(), "Environment", configurationService.getEnvironment(), "Client", authenticationRequest.getClientID().getValue()));
            sessionService.save(session.setAuthenticated(true).setNewAccount(EXISTING));
            auditService.submitAuditEvent(OidcAuditableEvent.AUTH_CODE_ISSUED, context.getAwsRequestId(), session.getSessionId(), authenticationRequest.getClientID().getValue(), AuditService.UNKNOWN, session.getEmailAddress(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
            return generateResponse(new AuthCodeResponse(authenticationResponse.toURI().toString()));
        } catch (ClientNotFoundException e) {
            AuthenticationErrorResponse errorResponse = authorizationService.generateAuthenticationErrorResponse(authenticationRequest, OAuth2Error.INVALID_CLIENT);
            return generateResponse(new AuthCodeResponse(errorResponse.toURI().toString()));
        } catch (URISyntaxException e) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1016);
        }
    });
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) AuthCodeResponse(uk.gov.di.authentication.oidc.entity.AuthCodeResponse) AuthenticationErrorResponse(com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse) ClientNotFoundException(uk.gov.di.authentication.shared.exceptions.ClientNotFoundException) VectorOfTrust(uk.gov.di.authentication.shared.entity.VectorOfTrust) URISyntaxException(java.net.URISyntaxException) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) ParseException(com.nimbusds.oauth2.sdk.ParseException) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) Session(uk.gov.di.authentication.shared.entity.Session) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession)

Example 12 with AuthenticationRequest

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

the class TokenHandlerTest method shouldReturn200ForSuccessfulTokenRequest.

@ParameterizedTest
@MethodSource("validVectorValues")
public void shouldReturn200ForSuccessfulTokenRequest(String vectorValue) 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);
    when(tokenService.validateTokenRequestParams(anyString())).thenReturn(Optional.empty());
    when(clientService.getClient(eq(CLIENT_ID))).thenReturn(Optional.of(clientRegistry));
    when(tokenService.validatePrivateKeyJWT(anyString(), eq(clientRegistry.getPublicKey()), eq(BASE_URI), eq(CLIENT_ID))).thenReturn(Optional.empty());
    String authCode = new AuthorizationCode().toString();
    when(authorisationCodeService.getExchangeDataForCode(authCode)).thenReturn(Optional.of(new AuthCodeExchangeData().setEmail(TEST_EMAIL).setClientSessionId(CLIENT_SESSION_ID)));
    AuthenticationRequest authenticationRequest = generateAuthRequest(JsonArrayHelper.jsonArrayOf(vectorValue));
    VectorOfTrust vtr = VectorOfTrust.parseFromAuthRequestAttribute(authenticationRequest.getCustomParameter("vtr"));
    when(clientSessionService.getClientSession(CLIENT_SESSION_ID)).thenReturn(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(), clientRegistry.isConsentRequired(), null)).thenReturn(tokenResponse);
    APIGatewayProxyResponseEvent result = generateApiGatewayRequest(privateKeyJWT, authCode);
    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) 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 13 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) throws ClientNotFoundException, URISyntaxException, JsonProcessingException {
    AuthorizationCode authorizationCode = new AuthorizationCode();
    AuthenticationRequest authRequest = generateValidSessionAndAuthRequest(requestedLevel);
    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(eq(CLIENT_SESSION_ID), eq(EMAIL))).thenReturn(authorizationCode);
    when(authorizationService.generateSuccessfulAuthResponse(any(AuthenticationRequest.class), any(AuthorizationCode.class))).thenReturn(authSuccessResponse);
    APIGatewayProxyResponseEvent response = generateApiRequest();
    assertThat(response, hasStatus(200));
    AuthCodeResponse authCodeResponse = new ObjectMapper().readValue(response.getBody(), AuthCodeResponse.class);
    assertThat(authCodeResponse.getLocation(), equalTo(authSuccessResponse.toURI().toString()));
    assertThat(session.getCurrentCredentialStrength(), equalTo(finalLevel));
    verify(sessionService).save(session.setAuthenticated(true));
    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) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 14 with AuthenticationRequest

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

the class AuthorizationServiceTest method shouldReturnErrorWhenInvalidVtrIsIncludedInAuthRequest.

@Test
void shouldReturnErrorWhenInvalidVtrIsIncludedInAuthRequest() {
    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())));
    AuthenticationRequest authRequest = new AuthenticationRequest.Builder(responseType, scope, CLIENT_ID, REDIRECT_URI).state(new State()).nonce(new Nonce()).customParameter("vtr", jsonArrayOf("Cm")).build();
    Optional<ErrorObject> errorObject = authorizationService.validateAuthRequest(authRequest);
    assertThat(errorObject, equalTo(Optional.of(new ErrorObject(OAuth2Error.INVALID_REQUEST_CODE, "Request vtr not valid"))));
}
Also used : Nonce(com.nimbusds.openid.connect.sdk.Nonce) Scope(com.nimbusds.oauth2.sdk.Scope) State(com.nimbusds.oauth2.sdk.id.State) 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 15 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() throws URISyntaxException {
    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);
    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