Search in sources :

Example 21 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class ClientSubjectHelperTest method shouldReturnDifferentSubjectIDForMultipleClientsWithDifferentSectors.

@Test
void shouldReturnDifferentSubjectIDForMultipleClientsWithDifferentSectors() {
    stubAuthenticationService();
    KeyPair keyPair = generateRsaKeyPair();
    UserProfile userProfile = generateUserProfile();
    ClientRegistry clientRegistry1 = generateClientRegistryPairwise(keyPair, "test-client-id-1", "pairwise", "https://test.com");
    ClientRegistry clientRegistry2 = generateClientRegistryPairwise(keyPair, "test-client-id-2", "pairwise", "https://not-test.com");
    Subject subject1 = ClientSubjectHelper.getSubject(userProfile, clientRegistry1, authenticationService);
    Subject subject2 = ClientSubjectHelper.getSubject(userProfile, clientRegistry2, authenticationService);
    assertNotEquals(subject1, subject2);
}
Also used : KeyPair(java.security.KeyPair) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) Subject(com.nimbusds.oauth2.sdk.id.Subject) Test(org.junit.jupiter.api.Test)

Example 22 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class DynamoService method signUp.

@Override
public void signUp(String email, String password, Subject subject, TermsAndConditions termsAndConditions) {
    String dateTime = LocalDateTime.now().toString();
    String hashedPassword = hashPassword(password);
    UserCredentials userCredentials = new UserCredentials().setEmail(email.toLowerCase(Locale.ROOT)).setSubjectID(subject.toString()).setPassword(hashedPassword).setCreated(dateTime).setUpdated(dateTime);
    UserProfile userProfile = new UserProfile().setEmail(email.toLowerCase(Locale.ROOT)).setSubjectID(subject.toString()).setEmailVerified(true).setCreated(dateTime).setUpdated(dateTime).setPublicSubjectID((new Subject()).toString()).setTermsAndConditions(termsAndConditions).setLegacySubjectID(null);
    userCredentialsMapper.save(userCredentials);
    userProfileMapper.save(userProfile);
}
Also used : UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) UserCredentials(uk.gov.di.authentication.shared.entity.UserCredentials) Subject(com.nimbusds.oauth2.sdk.id.Subject)

Example 23 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject 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 24 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class ResetPasswordRequestHandlerTest method shouldReturn200AndPutMessageOnQueueForAValidCodeFlowRequest.

@Test
void shouldReturn200AndPutMessageOnQueueForAValidCodeFlowRequest() throws Json.JsonException {
    String persistentId = "some-persistent-id-value";
    Map<String, String> headers = new HashMap<>();
    headers.put(PersistentIdHelper.PERSISTENT_ID_HEADER_NAME, persistentId);
    headers.put("Session-Id", session.getSessionId());
    Subject subject = new Subject("subject_1");
    when(authenticationService.getSubjectFromEmail(TEST_EMAIL_ADDRESS)).thenReturn(subject);
    NotifyRequest notifyRequest = new NotifyRequest(TEST_EMAIL_ADDRESS, RESET_PASSWORD_WITH_CODE, TEST_SIX_DIGIT_CODE);
    String serialisedRequest = objectMapper.writeValueAsString(notifyRequest);
    usingValidSession();
    APIGatewayProxyRequestEvent event = new APIGatewayProxyRequestEvent();
    event.setRequestContext(contextWithSourceIp("123.123.123.123"));
    event.setHeaders(headers);
    event.setBody(format("{ \"email\": \"%s\", \"useCodeFlow\": true }", TEST_EMAIL_ADDRESS));
    APIGatewayProxyResponseEvent result = handler.handleRequest(event, context);
    assertEquals(204, result.getStatusCode());
    verify(awsSqsClient).send(argThat(containsJsonString(serialisedRequest)));
    verify(codeStorageService).saveOtpCode(TEST_EMAIL_ADDRESS, TEST_SIX_DIGIT_CODE, CODE_EXPIRY_TIME, RESET_PASSWORD_WITH_CODE);
    verify(sessionService).save(argThat(this::isSessionWithEmailSent));
    verify(auditService).submitAuditEvent(FrontendAuditableEvent.PASSWORD_RESET_REQUESTED, context.getAwsRequestId(), session.getSessionId(), AuditService.UNKNOWN, AuditService.UNKNOWN, TEST_EMAIL_ADDRESS, "123.123.123.123", AuditService.UNKNOWN, persistentId);
}
Also used : APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) HashMap(java.util.HashMap) JsonArgumentMatcher.containsJsonString(uk.gov.di.authentication.sharedtest.matchers.JsonArgumentMatcher.containsJsonString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) NotifyRequest(uk.gov.di.authentication.shared.entity.NotifyRequest) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) Subject(com.nimbusds.oauth2.sdk.id.Subject) Test(org.junit.jupiter.api.Test)

Example 25 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class ResetPasswordRequestHandlerTest method shouldReturn400IfUserHasExceededPasswordResetCount.

@Test
public void shouldReturn400IfUserHasExceededPasswordResetCount() {
    Subject subject = new Subject("subject_1");
    String sessionId = "1233455677";
    when(authenticationService.getSubjectFromEmail(TEST_EMAIL_ADDRESS)).thenReturn(subject);
    when(configurationService.getBlockedEmailDuration()).thenReturn(BLOCKED_EMAIL_DURATION);
    Session session = mock(Session.class);
    when(session.getEmailAddress()).thenReturn(TEST_EMAIL_ADDRESS);
    when(session.getSessionId()).thenReturn(sessionId);
    when(session.validateSession(TEST_EMAIL_ADDRESS)).thenReturn(true);
    when(session.getPasswordResetCount()).thenReturn(5);
    when(sessionService.getSessionFromRequestHeaders(anyMap())).thenReturn(Optional.of(session));
    APIGatewayProxyRequestEvent event = new APIGatewayProxyRequestEvent();
    event.setHeaders(Map.of("Session-Id", sessionId));
    event.setBody(format("{ \"email\": \"%s\" }", TEST_EMAIL_ADDRESS));
    APIGatewayProxyResponseEvent result = handler.handleRequest(event, context);
    assertEquals(400, result.getStatusCode());
    verify(codeStorageService).saveBlockedForEmail(TEST_EMAIL_ADDRESS, PASSWORD_RESET_BLOCKED_KEY_PREFIX, BLOCKED_EMAIL_DURATION);
    verify(session).resetPasswordResetCount();
    assertThat(result, hasJsonBody(ErrorResponse.ERROR_1022));
}
Also used : APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) JsonArgumentMatcher.containsJsonString(uk.gov.di.authentication.sharedtest.matchers.JsonArgumentMatcher.containsJsonString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) Subject(com.nimbusds.oauth2.sdk.id.Subject) Session(uk.gov.di.authentication.shared.entity.Session) Test(org.junit.jupiter.api.Test)

Aggregations

Subject (com.nimbusds.oauth2.sdk.id.Subject)59 Test (org.junit.jupiter.api.Test)36 SignedJWT (com.nimbusds.jwt.SignedJWT)22 Date (java.util.Date)22 ApiGatewayHandlerIntegrationTest (uk.gov.di.authentication.sharedtest.basetest.ApiGatewayHandlerIntegrationTest)19 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)18 KeyPair (java.security.KeyPair)16 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)15 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)13 ParseException (com.nimbusds.oauth2.sdk.ParseException)12 Scope (com.nimbusds.oauth2.sdk.Scope)12 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)11 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)11 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)10 ECKeyGenerator (com.nimbusds.jose.jwk.gen.ECKeyGenerator)9 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)9 ECDSASigner (com.nimbusds.jose.crypto.ECDSASigner)8 Issuer (com.nimbusds.oauth2.sdk.id.Issuer)8 IDTokenClaimsSet (com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet)8 LocalDateTime (java.time.LocalDateTime)8