Search in sources :

Example 16 with JsonException

use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.

the class IPVAuthorisationService method isStateValid.

private boolean isStateValid(String sessionId, String responseState) {
    var value = Optional.ofNullable(redisConnectionService.getValue(STATE_STORAGE_PREFIX + sessionId));
    if (value.isEmpty()) {
        LOG.info("No state found in Redis");
        return false;
    }
    State storedState;
    try {
        storedState = objectMapper.readValue(value.get(), State.class);
    } catch (JsonException e) {
        LOG.info("Error when deserializing state from redis");
        return false;
    }
    LOG.info("Response state: {} and Stored state: {}. Are equal: {}", responseState, storedState.getValue(), responseState.equals(storedState.getValue()));
    return responseState.equals(storedState.getValue());
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) State(com.nimbusds.oauth2.sdk.id.State)

Example 17 with JsonException

use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.

the class TokenService method generateAndStoreAccessToken.

private AccessToken generateAndStoreAccessToken(String clientId, Subject internalSubject, List<String> scopes, Subject subject, OIDCClaimsRequest claimsRequest) {
    LOG.info("Generating AccessToken");
    Date expiryDate = NowHelper.nowPlus(configService.getAccessTokenExpiry(), ChronoUnit.SECONDS);
    var jwtID = UUID.randomUUID().toString();
    LOG.info("AccessToken being created with JWTID: {}", jwtID);
    JWTClaimsSet.Builder claimSetBuilder = new JWTClaimsSet.Builder().claim("scope", scopes).issuer(configService.getOidcApiBaseURL().get()).expirationTime(expiryDate).issueTime(NowHelper.now()).claim("client_id", clientId).subject(subject.getValue()).jwtID(jwtID);
    if (Objects.nonNull(claimsRequest)) {
        claimSetBuilder.claim("claims", claimsRequest.getUserInfoClaimsRequest().getEntries().stream().map(ClaimsSetRequest.Entry::getClaimName).collect(Collectors.toList()));
    }
    SignedJWT signedJWT = generateSignedJWT(claimSetBuilder.build(), Optional.empty());
    AccessToken accessToken = new BearerAccessToken(signedJWT.serialize());
    try {
        redisConnectionService.saveWithExpiry(ACCESS_TOKEN_PREFIX + clientId + "." + subject.getValue(), objectMapper.writeValueAsString(new AccessTokenStore(accessToken.getValue(), internalSubject.getValue())), configService.getAccessTokenExpiry());
    } catch (JsonException e) {
        LOG.error("Unable to save access token to Redis");
        throw new RuntimeException(e);
    }
    return accessToken;
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) AccessTokenStore(uk.gov.di.authentication.shared.entity.AccessTokenStore) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) SignedJWT(com.nimbusds.jwt.SignedJWT) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Date(java.util.Date)

Example 18 with JsonException

use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.

the class DocAppAuthorizeHandler method docAppAuthoriseRequestHandler.

public APIGatewayProxyResponseEvent docAppAuthoriseRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        try {
            LOG.info("DocAppAuthorizeHandler received request");
            var session = sessionService.getSessionFromRequestHeaders(input.getHeaders()).orElse(null);
            var clientSession = clientSessionService.getClientSessionFromRequestHeaders(input.getHeaders()).orElse(null);
            if (Objects.isNull(session)) {
                LOG.warn("Session cannot be found");
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1000);
            }
            if (Objects.isNull(clientSession)) {
                LOG.warn("ClientSession cannot be found");
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1018);
            }
            attachSessionIdToLogs(session);
            var clientID = new ClientID(configurationService.getDocAppAuthorisationClientId());
            var state = new State();
            var encryptedJWT = authorisationService.constructRequestJWT(state, clientSession.getDocAppSubjectId());
            var authRequestBuilder = new AuthorizationRequest.Builder(new ResponseType(ResponseType.Value.CODE), clientID).endpointURI(configurationService.getDocAppAuthorisationURI()).requestObject(encryptedJWT);
            var authorisationRequest = authRequestBuilder.build();
            authorisationService.storeState(session.getSessionId(), state);
            auditService.submitAuditEvent(DocAppAuditableEvent.DOC_APP_AUTHORISATION_REQUESTED, context.getAwsRequestId(), session.getSessionId(), AuditService.UNKNOWN, clientSession.getDocAppSubjectId().toString(), AuditService.UNKNOWN, IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
            LOG.info("DocAppAuthorizeHandler successfully processed request, redirect URI {}", authorisationRequest.toURI().toString());
            return generateApiGatewayProxyResponse(200, new DocAppAuthorisationResponse(authorisationRequest.toURI().toString()));
        } catch (JsonException e) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
        }
    });
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) State(com.nimbusds.oauth2.sdk.id.State) DocAppAuthorisationResponse(uk.gov.di.authentication.app.entity.DocAppAuthorisationResponse) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

Example 19 with JsonException

use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.

the class DocAppAuthorisationService method isStateValid.

private boolean isStateValid(String sessionId, String responseState) {
    var value = Optional.ofNullable(redisConnectionService.getValue(STATE_STORAGE_PREFIX + sessionId));
    if (value.isEmpty()) {
        LOG.info("No Doc Checking App state found in Redis");
        return false;
    }
    State storedState;
    try {
        storedState = objectMapper.readValue(value.get(), State.class);
    } catch (JsonException e) {
        LOG.info("Error when deserializing state from redis");
        return false;
    }
    LOG.info("Response state: {} and Stored state: {}. Are equal: {}", responseState, storedState.getValue(), responseState.equals(storedState.getValue()));
    return responseState.equals(storedState.getValue());
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) State(com.nimbusds.oauth2.sdk.id.State)

Example 20 with JsonException

use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.

the class UpdateClientConfigHandler method updateClientRequestHandler.

public APIGatewayProxyResponseEvent updateClientRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        String ipAddress = IpAddressHelper.extractIpAddress(input);
        auditService.submitAuditEvent(UPDATE_CLIENT_REQUEST_RECEIVED, context.getAwsRequestId(), AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, ipAddress, AuditService.UNKNOWN, AuditService.UNKNOWN);
        try {
            String clientId = input.getPathParameters().get("clientId");
            attachLogFieldToLogs(CLIENT_ID, clientId);
            LOG.info("Update client config request received");
            var updateClientConfigRequest = objectMapper.readValue(input.getBody(), UpdateClientConfigRequest.class);
            if (!clientService.isValidClient(clientId)) {
                auditService.submitAuditEvent(UPDATE_CLIENT_REQUEST_ERROR, context.getAwsRequestId(), AuditService.UNKNOWN, clientId, AuditService.UNKNOWN, AuditService.UNKNOWN, ipAddress, AuditService.UNKNOWN, AuditService.UNKNOWN);
                LOG.warn("Invalid client id");
                return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_CLIENT.toJSONObject().toJSONString());
            }
            Optional<ErrorObject> errorResponse = validationService.validateClientUpdateConfig(updateClientConfigRequest);
            if (errorResponse.isPresent()) {
                LOG.warn("Failed validation. ErrorCode: {}. ErrorDescription: {}", errorResponse.get().getCode(), errorResponse.get().getDescription());
                auditService.submitAuditEvent(UPDATE_CLIENT_REQUEST_ERROR, context.getAwsRequestId(), AuditService.UNKNOWN, clientId, AuditService.UNKNOWN, AuditService.UNKNOWN, ipAddress, AuditService.UNKNOWN, AuditService.UNKNOWN);
                return generateApiGatewayProxyResponse(400, errorResponse.get().toJSONObject().toJSONString());
            }
            ClientRegistry clientRegistry = clientService.updateClient(clientId, updateClientConfigRequest);
            ClientRegistrationResponse clientRegistrationResponse = new ClientRegistrationResponse(clientRegistry.getClientName(), clientRegistry.getClientID(), clientRegistry.getRedirectUrls(), clientRegistry.getContacts(), clientRegistry.getScopes(), clientRegistry.getPostLogoutRedirectUrls(), clientRegistry.getBackChannelLogoutUri(), clientRegistry.getServiceType(), clientRegistry.getSubjectType(), clientRegistry.getClaims(), clientRegistry.getSectorIdentifierUri(), clientRegistry.getClientType());
            LOG.info("Client updated");
            return generateApiGatewayProxyResponse(200, clientRegistrationResponse);
        } catch (JsonException | NullPointerException e) {
            auditService.submitAuditEvent(UPDATE_CLIENT_REQUEST_ERROR, context.getAwsRequestId(), AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, ipAddress, AuditService.UNKNOWN, AuditService.UNKNOWN);
            LOG.warn("Invalid Client registration request. Missing parameters from request");
            return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_REQUEST.toJSONObject().toJSONString());
        }
    });
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) ClientRegistrationResponse(uk.gov.di.authentication.clientregistry.entity.ClientRegistrationResponse) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry)

Aggregations

JsonException (uk.gov.di.authentication.shared.serialization.Json.JsonException)25 ClientRegistry (uk.gov.di.authentication.shared.entity.ClientRegistry)7 ErrorResponse (uk.gov.di.authentication.shared.entity.ErrorResponse)7 ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse (uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)7 Subject (com.nimbusds.oauth2.sdk.id.Subject)6 NotifyRequest (uk.gov.di.accountmanagement.entity.NotifyRequest)5 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)5 State (com.nimbusds.oauth2.sdk.id.State)4 NotifyRequest (uk.gov.di.authentication.shared.entity.NotifyRequest)4 SQSMessage (com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage)3 SignedJWT (com.nimbusds.jwt.SignedJWT)3 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)3 NoSuchElementException (java.util.NoSuchElementException)3 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 ParseException (com.nimbusds.oauth2.sdk.ParseException)2 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)2 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 SdkClientException (software.amazon.awssdk.core.exception.SdkClientException)2