use of uk.gov.di.authentication.shared.entity.ClientRegistry 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()));
}
use of uk.gov.di.authentication.shared.entity.ClientRegistry in project di-authentication-api by alphagov.
the class TokenHandlerTest method shouldReturn200ForSuccessfulRefreshTokenRequest.
@Test
public void shouldReturn200ForSuccessfulRefreshTokenRequest() throws JOSEException, JsonProcessingException {
SignedJWT signedRefreshToken = createSignedRefreshToken();
KeyPair keyPair = generateRsaKeyPair();
RefreshToken refreshToken = new RefreshToken(signedRefreshToken.serialize());
OIDCTokenResponse tokenResponse = new OIDCTokenResponse(new OIDCTokens(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());
when(tokenValidationService.validateRefreshTokenSignatureAndExpiry(refreshToken)).thenReturn(true);
when(tokenValidationService.validateRefreshTokenScopes(SCOPES.toStringList(), SCOPES.toStringList())).thenReturn(true);
RefreshTokenStore tokenStore = new RefreshTokenStore(singletonList(refreshToken.getValue()), INTERNAL_SUBJECT.getValue());
String redisKey = REFRESH_TOKEN_PREFIX + CLIENT_ID + "." + PUBLIC_SUBJECT.getValue();
String tokenStoreString = new ObjectMapper().writeValueAsString(tokenStore);
when(redisConnectionService.getValue(redisKey)).thenReturn(tokenStoreString);
when(tokenService.generateRefreshTokenResponse(eq(CLIENT_ID), eq(INTERNAL_SUBJECT), eq(SCOPES.toStringList()), eq(PUBLIC_SUBJECT))).thenReturn(tokenResponse);
APIGatewayProxyResponseEvent result = generateApiGatewayRefreshRequest(privateKeyJWT, refreshToken.getValue());
assertThat(result, hasStatus(200));
assertTrue(result.getBody().contains(refreshToken.getValue()));
assertTrue(result.getBody().contains(accessToken.getValue()));
verify(redisConnectionService, times(1)).deleteValue(redisKey);
}
use of uk.gov.di.authentication.shared.entity.ClientRegistry in project di-authentication-api by alphagov.
the class TokenHandlerTest method shouldReturn200ForRefreshTokenRequestWhenMultipleRefreshTokensAreStored.
@Test
public void shouldReturn200ForRefreshTokenRequestWhenMultipleRefreshTokensAreStored() throws JOSEException, JsonProcessingException {
SignedJWT signedRefreshToken = createSignedRefreshToken();
KeyPair keyPair = generateRsaKeyPair();
RefreshToken refreshToken = new RefreshToken(signedRefreshToken.serialize());
RefreshToken refreshToken2 = new RefreshToken();
OIDCTokenResponse tokenResponse = new OIDCTokenResponse(new OIDCTokens(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());
when(tokenValidationService.validateRefreshTokenSignatureAndExpiry(refreshToken)).thenReturn(true);
when(tokenValidationService.validateRefreshTokenScopes(SCOPES.toStringList(), SCOPES.toStringList())).thenReturn(true);
RefreshTokenStore tokenStore = new RefreshTokenStore(List.of(refreshToken.getValue(), refreshToken2.getValue()), INTERNAL_SUBJECT.getValue());
String redisKey = REFRESH_TOKEN_PREFIX + CLIENT_ID + "." + PUBLIC_SUBJECT.getValue();
String tokenStoreString = new ObjectMapper().writeValueAsString(tokenStore);
when(redisConnectionService.getValue(redisKey)).thenReturn(tokenStoreString);
when(tokenService.generateRefreshTokenResponse(eq(CLIENT_ID), eq(INTERNAL_SUBJECT), eq(SCOPES.toStringList()), eq(PUBLIC_SUBJECT))).thenReturn(tokenResponse);
APIGatewayProxyResponseEvent result = generateApiGatewayRefreshRequest(privateKeyJWT, refreshToken.getValue());
assertThat(result, hasStatus(200));
assertTrue(result.getBody().contains(refreshToken.getValue()));
assertTrue(result.getBody().contains(accessToken.getValue()));
String updatedTokenstore = new ObjectMapper().writeValueAsString(new RefreshTokenStore(List.of(refreshToken2.getValue()), INTERNAL_SUBJECT.getValue()));
verify(redisConnectionService, times(1)).saveWithExpiry(redisKey, updatedTokenstore, 1234L);
}
use of uk.gov.di.authentication.shared.entity.ClientRegistry in project di-authentication-api by alphagov.
the class StartServiceTest method buildUserContext.
private UserContext buildUserContext(String vtrValue, boolean consentRequired, boolean cookieConsentShared) {
var authRequest = new AuthenticationRequest.Builder(new ResponseType(ResponseType.Value.CODE), SCOPES, CLIENT_ID, REDIRECT_URI).state(new State()).nonce(new Nonce()).customParameter("vtr", vtrValue).build();
var clientSession = new ClientSession(authRequest.toParameters(), LocalDateTime.now(), VectorOfTrust.getDefaults());
var clientRegistry = new ClientRegistry().setClientID(CLIENT_ID.getValue()).setClientName(CLIENT_NAME).setConsentRequired(consentRequired).setCookieConsentShared(cookieConsentShared);
return UserContext.builder(SESSION).withClientSession(clientSession).withClient(clientRegistry).build();
}
use of uk.gov.di.authentication.shared.entity.ClientRegistry in project di-authentication-api by alphagov.
the class ResetPasswordHandler method handleRequestWithUserContext.
@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, ResetPasswordWithCodeRequest request, UserContext userContext) {
LOG.info("Request received to ResetPasswordHandler");
try {
Optional<ErrorResponse> errorResponse = validationService.validatePassword(request.getPassword());
if (errorResponse.isPresent()) {
return generateApiGatewayProxyErrorResponse(400, errorResponse.get());
}
Optional<String> subject = codeStorageService.getSubjectWithPasswordResetCode(request.getCode());
if (subject.isEmpty()) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1021);
}
UserCredentials userCredentials = authenticationService.getUserCredentialsFromSubject(subject.get());
if (userCredentials.getPassword() != null) {
if (verifyPassword(userCredentials.getPassword(), request.getPassword())) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1024);
}
} else {
LOG.info("Resetting password for migrated user");
}
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 (JsonProcessingException | ConstraintViolationException e) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
}
LOG.info("Generating successful response");
return generateEmptySuccessApiGatewayResponse();
}
Aggregations