Search in sources :

Example 1 with JsonException

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

the class TokenService method generateAndStoreRefreshToken.

private RefreshToken generateAndStoreRefreshToken(String clientId, Subject internalSubject, List<String> scopes, Subject subject) {
    LOG.info("Generating RefreshToken");
    Date expiryDate = NowHelper.nowPlus(configService.getSessionExpiry(), ChronoUnit.SECONDS);
    var jwtId = IdGenerator.generate();
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("scope", scopes).issuer(configService.getOidcApiBaseURL().get()).expirationTime(expiryDate).issueTime(NowHelper.now()).claim("client_id", clientId).subject(subject.getValue()).jwtID(jwtId).build();
    SignedJWT signedJWT = generateSignedJWT(claimsSet, Optional.empty());
    RefreshToken refreshToken = new RefreshToken(signedJWT.serialize());
    String redisKey = REFRESH_TOKEN_PREFIX + jwtId;
    var store = new RefreshTokenStore(refreshToken.getValue(), internalSubject.toString());
    try {
        redisConnectionService.saveWithExpiry(redisKey, objectMapper.writeValueAsString(store), configService.getSessionExpiry());
    } catch (JsonException e) {
        throw new RuntimeException("Error serializing refresh token store", e);
    }
    return refreshToken;
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) RefreshTokenStore(uk.gov.di.authentication.shared.entity.RefreshTokenStore) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) SignedJWT(com.nimbusds.jwt.SignedJWT) HashHelper.hashSha256String(uk.gov.di.authentication.shared.helpers.HashHelper.hashSha256String) Date(java.util.Date)

Example 2 with JsonException

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

the class ResetPasswordHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, ResetPasswordCompletionRequest request, UserContext userContext) {
    LOG.info("Request received to ResetPasswordHandler");
    try {
        Optional<ErrorResponse> errorResponse = ValidationHelper.validatePassword(request.getPassword());
        if (errorResponse.isPresent()) {
            return generateApiGatewayProxyErrorResponse(400, errorResponse.get());
        }
        UserCredentials userCredentials;
        if (nonNull(request.getCode())) {
            Optional<String> subject = codeStorageService.getSubjectWithPasswordResetCode(request.getCode());
            if (subject.isEmpty()) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1021);
            }
            userCredentials = authenticationService.getUserCredentialsFromSubject(subject.get());
        } else {
            userCredentials = authenticationService.getUserCredentialsFromEmail(userContext.getSession().getEmailAddress());
        }
        if (userCredentials.getPassword() != null) {
            if (verifyPassword(userCredentials.getPassword(), request.getPassword())) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1024);
            }
        } else {
            LOG.info("Resetting password for migrated user");
        }
        if (nonNull(request.getCode())) {
            codeStorageService.deleteSubjectWithPasswordResetCode(request.getCode());
        }
        authenticationService.updatePassword(userCredentials.getEmail(), request.getPassword());
        int incorrectPasswordCount = codeStorageService.getIncorrectPasswordCount(userCredentials.getEmail());
        if (incorrectPasswordCount != 0) {
            codeStorageService.deleteIncorrectPasswordCount(userCredentials.getEmail());
        }
        NotifyRequest notifyRequest = new NotifyRequest(userCredentials.getEmail(), NotificationType.PASSWORD_RESET_CONFIRMATION);
        LOG.info("Placing message on queue");
        sqsClient.send(serialiseRequest(notifyRequest));
        auditService.submitAuditEvent(FrontendAuditableEvent.PASSWORD_RESET_SUCCESSFUL, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, userCredentials.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
    } catch (JsonException e) {
        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
    }
    LOG.info("Generating successful response");
    return generateEmptySuccessApiGatewayResponse();
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) UserCredentials(uk.gov.di.authentication.shared.entity.UserCredentials) NotifyRequest(uk.gov.di.authentication.shared.entity.NotifyRequest) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)

Example 3 with JsonException

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

the class SendNotificationHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, SendNotificationRequest request, UserContext userContext) {
    attachSessionIdToLogs(userContext.getSession());
    attachLogFieldToLogs(PERSISTENT_SESSION_ID, extractPersistentIdFromHeaders(input.getHeaders()));
    attachLogFieldToLogs(LogFieldName.CLIENT_ID, userContext.getClient().map(ClientRegistry::getClientID).orElse("unknown"));
    try {
        if (!userContext.getSession().validateSession(request.getEmail())) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1000);
        }
        if (request.getNotificationType().equals(ACCOUNT_CREATED_CONFIRMATION)) {
            LOG.info("Placing message on queue for AccountCreatedConfirmation");
            NotifyRequest notifyRequest = new NotifyRequest(request.getEmail(), ACCOUNT_CREATED_CONFIRMATION);
            if (notTestClientWithValidTestEmail(userContext, ACCOUNT_CREATED_CONFIRMATION)) {
                sqsClient.send(objectMapper.writeValueAsString((notifyRequest)));
                LOG.info("AccountCreatedConfirmation email placed on queue");
            }
            return generateEmptySuccessApiGatewayResponse();
        }
        Optional<ErrorResponse> codeRequestValid = isCodeRequestAttemptValid(request.getEmail(), userContext.getSession(), request.getNotificationType());
        if (codeRequestValid.isPresent()) {
            return generateApiGatewayProxyErrorResponse(400, codeRequestValid.get());
        }
        switch(request.getNotificationType()) {
            case VERIFY_EMAIL:
                return handleNotificationRequest(request.getEmail(), request.getNotificationType(), userContext.getSession(), userContext);
            case VERIFY_PHONE_NUMBER:
                if (request.getPhoneNumber() == null) {
                    return generateApiGatewayProxyResponse(400, ERROR_1011);
                }
                return handleNotificationRequest(PhoneNumberHelper.removeWhitespaceFromPhoneNumber(request.getPhoneNumber()), request.getNotificationType(), userContext.getSession(), userContext);
        }
        return generateApiGatewayProxyErrorResponse(400, ERROR_1002);
    } catch (SdkClientException ex) {
        LOG.error("Error sending message to queue");
        return generateApiGatewayProxyResponse(500, "Error sending message to queue");
    } catch (JsonException e) {
        return generateApiGatewayProxyErrorResponse(400, ERROR_1001);
    } catch (ClientNotFoundException e) {
        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1015);
    }
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) ClientNotFoundException(uk.gov.di.authentication.shared.exceptions.ClientNotFoundException) SdkClientException(software.amazon.awssdk.core.exception.SdkClientException) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) NotifyRequest(uk.gov.di.authentication.shared.entity.NotifyRequest) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)

Example 4 with JsonException

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

the class SignUpHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, SignupRequest request, UserContext userContext) {
    attachSessionIdToLogs(userContext.getSession());
    attachLogFieldToLogs(PERSISTENT_SESSION_ID, extractPersistentIdFromHeaders(input.getHeaders()));
    attachLogFieldToLogs(CLIENT_ID, userContext.getClient().map(ClientRegistry::getClientID).orElse("unknown"));
    LOG.info("Received request");
    Optional<ErrorResponse> passwordValidationErrors = ValidationHelper.validatePassword(request.getPassword());
    if (passwordValidationErrors.isEmpty()) {
        if (authenticationService.userExists(request.getEmail())) {
            auditService.submitAuditEvent(FrontendAuditableEvent.CREATE_ACCOUNT_EMAIL_ALREADY_EXISTS, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, request.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1009);
        }
        authenticationService.signUp(request.getEmail(), request.getPassword(), new Subject(), new TermsAndConditions(configurationService.getTermsAndConditionsVersion(), LocalDateTime.now(ZoneId.of("UTC")).toString()));
        var consentRequired = ConsentHelper.userHasNotGivenConsent(userContext);
        auditService.submitAuditEvent(FrontendAuditableEvent.CREATE_ACCOUNT, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, request.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
        sessionService.save(userContext.getSession().setEmailAddress(request.getEmail()).setNewAccount(NEW));
        LOG.info("Successfully processed request");
        try {
            return generateApiGatewayProxyResponse(200, new SignUpResponse(consentRequired));
        } catch (JsonException e) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
        }
    } else {
        return generateApiGatewayProxyErrorResponse(400, passwordValidationErrors.get());
    }
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) SignUpResponse(uk.gov.di.authentication.frontendapi.entity.SignUpResponse) TermsAndConditions(uk.gov.di.authentication.shared.entity.TermsAndConditions) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) Subject(com.nimbusds.oauth2.sdk.id.Subject) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)

Example 5 with JsonException

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

the class CheckUserExistsHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, CheckUserExistsRequest request, UserContext userContext) {
    attachSessionIdToLogs(userContext.getSession());
    attachLogFieldToLogs(PERSISTENT_SESSION_ID, extractPersistentIdFromHeaders(input.getHeaders()));
    attachLogFieldToLogs(CLIENT_ID, userContext.getClient().map(ClientRegistry::getClientID).orElse("unknown"));
    try {
        LOG.info("Processing request");
        String emailAddress = request.getEmail().toLowerCase();
        Optional<ErrorResponse> errorResponse = ValidationHelper.validateEmailAddress(emailAddress);
        String persistentSessionId = PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders());
        if (errorResponse.isPresent()) {
            auditService.submitAuditEvent(FrontendAuditableEvent.CHECK_USER_INVALID_EMAIL, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, emailAddress, IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
            return generateApiGatewayProxyErrorResponse(400, errorResponse.get());
        }
        boolean userExists = authenticationService.userExists(emailAddress);
        userContext.getSession().setEmailAddress(emailAddress);
        AuditableEvent auditableEvent;
        if (userExists) {
            auditableEvent = FrontendAuditableEvent.CHECK_USER_KNOWN_EMAIL;
        } else {
            auditableEvent = FrontendAuditableEvent.CHECK_USER_NO_ACCOUNT_WITH_EMAIL;
        }
        auditService.submitAuditEvent(auditableEvent, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, emailAddress, IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
        CheckUserExistsResponse checkUserExistsResponse = new CheckUserExistsResponse(emailAddress, userExists);
        sessionService.save(userContext.getSession());
        LOG.info("Successfully processed request");
        return generateApiGatewayProxyResponse(200, checkUserExistsResponse);
    } catch (JsonException e) {
        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
    }
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) CheckUserExistsResponse(uk.gov.di.authentication.frontendapi.entity.CheckUserExistsResponse) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse) FrontendAuditableEvent(uk.gov.di.authentication.frontendapi.domain.FrontendAuditableEvent) AuditableEvent(uk.gov.di.authentication.shared.domain.AuditableEvent)

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