Search in sources :

Example 71 with AuthenticationRequest

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

the class AuthorizationServiceTest method shouldSuccessfullyValidateAuthRequestWhenIdentityValuesAreIncludedInVtrAttribute.

@Test
void shouldSuccessfullyValidateAuthRequestWhenIdentityValuesAreIncludedInVtrAttribute() {
    when(ipvCapacityService.isIPVCapacityAvailable()).thenReturn(true);
    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("P2.Cl.Cm", "P2.Cl"), Optional.empty());
    var errorObject = authorizationService.validateAuthRequest(authRequest);
    assertThat(errorObject, equalTo(Optional.empty()));
}
Also used : Scope(com.nimbusds.oauth2.sdk.Scope) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ResponseType(com.nimbusds.oauth2.sdk.ResponseType) Test(org.junit.jupiter.api.Test)

Example 72 with AuthenticationRequest

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

the class AuthCodeHandler method authCodeRequestHandler.

public APIGatewayProxyResponseEvent authCodeRequestHandler(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()));
        }
        addAnnotation("client_id", String.valueOf(clientSession.getAuthRequestParams().get("client_id")));
        URI redirectUri = authenticationRequest.getRedirectionURI();
        State state = authenticationRequest.getState();
        try {
            boolean docCheckingUser = isDocCheckingAppUserWithSubjectId(clientSession);
            if (docCheckingUser) {
                redirectUri = URI.create(getRequestObjectClaim(authenticationRequest, "redirect_uri", String.class));
                state = new State(getRequestObjectClaim(authenticationRequest, "state", String.class));
            }
            if (!authorizationService.isClientRedirectUriValid(authenticationRequest.getClientID(), redirectUri)) {
                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(), clientSession);
            AuthenticationSuccessResponse authenticationResponse = authorizationService.generateSuccessfulAuthResponse(authenticationRequest, authCode, redirectUri, state);
            LOG.info("Successfully processed request");
            cloudwatchMetricsService.incrementCounter("SignIn", Map.of("Account", session.isNewAccount().name(), "Environment", configurationService.getEnvironment(), "Client", authenticationRequest.getClientID().getValue()));
            if (!docCheckingUser) {
                sessionService.save(session.setAuthenticated(true).setNewAccount(EXISTING));
            } else {
                LOG.info("Session not saved for DocCheckingAppUser");
            }
            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, redirectUri, state);
            return generateResponse(new AuthCodeResponse(errorResponse.toURI().toString()));
        }
    });
}
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) URI(java.net.URI) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse) State(com.nimbusds.oauth2.sdk.id.State) 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 73 with AuthenticationRequest

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

the class AuthorisationHandler method authoriseRequestHandler.

public APIGatewayProxyResponseEvent authoriseRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        var persistentSessionId = authorizationService.getExistingOrCreateNewPersistentSessionId(input.getHeaders());
        var ipAddress = IpAddressHelper.extractIpAddress(input);
        auditService.submitAuditEvent(OidcAuditableEvent.AUTHORISATION_REQUEST_RECEIVED, context.getAwsRequestId(), AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, ipAddress, AuditService.UNKNOWN, persistentSessionId);
        attachLogFieldToLogs(PERSISTENT_SESSION_ID, persistentSessionId);
        attachLogFieldToLogs(AWS_REQUEST_ID, context.getAwsRequestId());
        LOG.info("Received authentication request");
        Map<String, List<String>> queryStringParameters;
        AuthenticationRequest authRequest;
        try {
            queryStringParameters = input.getQueryStringParameters().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> List.of(entry.getValue())));
            authRequest = AuthenticationRequest.parse(queryStringParameters);
        } 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");
                throw new RuntimeException("Redirect URI or ClientID is missing from auth request", e);
            }
            LOG.warn("Authentication request could not be parsed", e);
            return generateErrorResponse(e.getRedirectionURI(), e.getState(), e.getResponseMode(), e.getErrorObject(), context, ipAddress, persistentSessionId);
        } catch (NullPointerException e) {
            LOG.warn("No query string parameters are present in the Authentication request", e);
            throw new RuntimeException("No query string parameters are present in the Authentication request", e);
        }
        Optional<AuthRequestError> authRequestError;
        if (authRequest.getRequestObject() != null && configurationService.isDocAppApiEnabled()) {
            LOG.info("RequestObject auth request received");
            authRequestError = requestObjectService.validateRequestObject(authRequest);
        } else {
            authRequestError = authorizationService.validateAuthRequest(authRequest);
        }
        return authRequestError.map(e -> generateErrorResponse(e.getRedirectURI(), authRequest.getState(), authRequest.getResponseMode(), e.getErrorObject(), context, ipAddress, persistentSessionId)).orElseGet(() -> getOrCreateSessionAndRedirect(queryStringParameters, sessionService.getSessionFromSessionCookie(input.getHeaders()), authRequest, context, ipAddress, persistentSessionId));
    });
}
Also used : AuthRequestError(uk.gov.di.authentication.oidc.entity.AuthRequestError) Prompt(com.nimbusds.openid.connect.sdk.Prompt) RequestObjectService(uk.gov.di.authentication.oidc.services.RequestObjectService) SessionService(uk.gov.di.authentication.shared.services.SessionService) URISyntaxException(java.net.URISyntaxException) LocalDateTime(java.time.LocalDateTime) Context(com.amazonaws.services.lambda.runtime.Context) ConfigurationService(uk.gov.di.authentication.shared.services.ConfigurationService) InstrumentationHelper.segmentedFunctionCall(uk.gov.di.authentication.shared.helpers.InstrumentationHelper.segmentedFunctionCall) RequestHandler(com.amazonaws.services.lambda.runtime.RequestHandler) ResponseMode(com.nimbusds.oauth2.sdk.ResponseMode) ResponseHeaders(uk.gov.di.authentication.shared.entity.ResponseHeaders) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) Session(uk.gov.di.authentication.shared.entity.Session) CLIENT_SESSION_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.CLIENT_SESSION_ID) PERSISTENT_SESSION_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.PERSISTENT_SESSION_ID) Map(java.util.Map) ParseException(com.nimbusds.oauth2.sdk.ParseException) URI(java.net.URI) AWS_REQUEST_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.AWS_REQUEST_ID) CLIENT_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.CLIENT_ID) LogLineHelper.updateAttachedSessionIdToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.updateAttachedSessionIdToLogs) MetadataPair.pair(uk.gov.di.authentication.shared.services.AuditService.MetadataPair.pair) WarmerHelper.isWarming(uk.gov.di.authentication.shared.helpers.WarmerHelper.isWarming) AuthenticationErrorResponse(com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse) OIDCError(com.nimbusds.openid.connect.sdk.OIDCError) URIBuilder(org.apache.http.client.utils.URIBuilder) OidcAuditableEvent(uk.gov.di.authentication.oidc.domain.OidcAuditableEvent) IpAddressHelper(uk.gov.di.authentication.shared.helpers.IpAddressHelper) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) AuditService(uk.gov.di.authentication.shared.services.AuditService) LogLineHelper.attachLogFieldToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.attachLogFieldToLogs) State(com.nimbusds.oauth2.sdk.id.State) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) CookieHelper(uk.gov.di.authentication.shared.helpers.CookieHelper) Collectors(java.util.stream.Collectors) ClientSessionService(uk.gov.di.authentication.shared.services.ClientSessionService) Objects(java.util.Objects) List(java.util.List) Logger(org.apache.logging.log4j.Logger) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) LogLineHelper.attachSessionIdToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.attachSessionIdToLogs) LogLineHelper.updateAttachedLogFieldToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.updateAttachedLogFieldToLogs) Optional(java.util.Optional) LogManager(org.apache.logging.log4j.LogManager) AuthorizationService(uk.gov.di.authentication.oidc.services.AuthorizationService) AuthRequestError(uk.gov.di.authentication.oidc.entity.AuthRequestError) List(java.util.List) ParseException(com.nimbusds.oauth2.sdk.ParseException) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest)

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