use of uk.gov.di.authentication.shared.entity.VectorOfTrust in project di-authentication-api by alphagov.
the class AuthCodeHandler method handleRequest.
@Override
public APIGatewayProxyResponseEvent handleRequest(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()));
}
try {
if (!authorizationService.isClientRedirectUriValid(authenticationRequest.getClientID(), authenticationRequest.getRedirectionURI())) {
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());
AuthenticationSuccessResponse authenticationResponse = authorizationService.generateSuccessfulAuthResponse(authenticationRequest, authCode);
LOG.info("Successfully processed request");
cloudwatchMetricsService.incrementCounter("SignIn", Map.of("Account", session.isNewAccount().name(), "Environment", configurationService.getEnvironment(), "Client", authenticationRequest.getClientID().getValue()));
sessionService.save(session.setAuthenticated(true).setNewAccount(EXISTING));
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);
return generateResponse(new AuthCodeResponse(errorResponse.toURI().toString()));
} catch (URISyntaxException e) {
return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1016);
}
});
}
use of uk.gov.di.authentication.shared.entity.VectorOfTrust 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.VectorOfTrust in project di-authentication-api by alphagov.
the class IdentityHelper method identityRequired.
public static boolean identityRequired(Map<String, List<String>> authRequestParams) {
AuthenticationRequest authRequest;
try {
authRequest = AuthenticationRequest.parse(authRequestParams);
} catch (ParseException e) {
throw new RuntimeException();
}
List<String> vtr = authRequest.getCustomParameter("vtr");
VectorOfTrust vectorOfTrust = VectorOfTrust.parseFromAuthRequestAttribute(vtr);
return Objects.nonNull(vectorOfTrust.getLevelOfConfidence());
}
use of uk.gov.di.authentication.shared.entity.VectorOfTrust in project di-authentication-api by alphagov.
the class TokenHandlerTest method shouldReturn200ForSuccessfulTokenRequest.
@ParameterizedTest
@MethodSource("validVectorValues")
public void shouldReturn200ForSuccessfulTokenRequest(String vectorValue, boolean clientRegistryConsent, boolean expectedConsentRequired, boolean clientIdInHeader) 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, clientRegistryConsent);
when(tokenService.validateTokenRequestParams(anyString())).thenReturn(Optional.empty());
when(clientService.getClient(eq(CLIENT_ID))).thenReturn(Optional.of(clientRegistry));
when(tokenService.getClientIDFromPrivateKeyJWT(anyString())).thenReturn(Optional.of(CLIENT_ID));
when(tokenService.validatePrivateKeyJWT(anyString(), eq(clientRegistry.getPublicKey()), eq(BASE_URI), eq(CLIENT_ID))).thenReturn(Optional.empty());
String authCode = new AuthorizationCode().toString();
AuthenticationRequest authenticationRequest = generateAuthRequest(JsonArrayHelper.jsonArrayOf(vectorValue));
VectorOfTrust vtr = VectorOfTrust.parseFromAuthRequestAttribute(authenticationRequest.getCustomParameter("vtr"));
when(authorisationCodeService.getExchangeDataForCode(authCode)).thenReturn(Optional.of(new AuthCodeExchangeData().setEmail(TEST_EMAIL).setClientSessionId(CLIENT_SESSION_ID).setClientSession(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(), expectedConsentRequired, null, false)).thenReturn(tokenResponse);
APIGatewayProxyResponseEvent result = generateApiGatewayRequest(privateKeyJWT, authCode, CLIENT_ID, clientIdInHeader);
assertThat(result, hasStatus(200));
assertTrue(result.getBody().contains(refreshToken.getValue()));
assertTrue(result.getBody().contains(accessToken.getValue()));
}
use of uk.gov.di.authentication.shared.entity.VectorOfTrust in project di-authentication-api by alphagov.
the class TokenHandlerTest method shouldReturn200ForSuccessfulDocAppJourneyTokenRequest.
@Test
void shouldReturn200ForSuccessfulDocAppJourneyTokenRequest() throws JOSEException {
KeyPair keyPair = generateRsaKeyPair();
UserProfile userProfile = generateUserProfile();
SignedJWT signedJWT = generateIDToken(DOC_APP_CLIENT_ID.getValue(), 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, false);
when(tokenService.validateTokenRequestParams(anyString())).thenReturn(Optional.empty());
when(clientService.getClient(DOC_APP_CLIENT_ID.getValue())).thenReturn(Optional.of(clientRegistry));
when(tokenService.getClientIDFromPrivateKeyJWT(anyString())).thenReturn(Optional.of(DOC_APP_CLIENT_ID.getValue()));
when(tokenService.validatePrivateKeyJWT(anyString(), eq(clientRegistry.getPublicKey()), eq(BASE_URI), eq(DOC_APP_CLIENT_ID.getValue()))).thenReturn(Optional.empty());
String authCode = new AuthorizationCode().toString();
AuthorizationRequest authenticationRequest = generateRequestObjectAuthRequest();
VectorOfTrust vtr = VectorOfTrust.parseFromAuthRequestAttribute(authenticationRequest.getCustomParameter("vtr"));
ClientSession clientSession = new ClientSession(authenticationRequest.toParameters(), LocalDateTime.now(), vtr);
clientSession.setDocAppSubjectId(DOC_APP_USER_PUBLIC_SUBJECT);
when(authorisationCodeService.getExchangeDataForCode(authCode)).thenReturn(Optional.of(new AuthCodeExchangeData().setEmail(TEST_EMAIL).setClientSessionId(CLIENT_SESSION_ID).setClientSession(clientSession)));
when(dynamoService.getUserProfileByEmail(TEST_EMAIL)).thenReturn(userProfile);
when(tokenService.generateTokenResponse(DOC_APP_CLIENT_ID.getValue(), DOC_APP_USER_PUBLIC_SUBJECT, new Scope(OIDCScopeValue.OPENID, DOC_CHECKING_APP), Map.of(), DOC_APP_USER_PUBLIC_SUBJECT, vtr.retrieveVectorOfTrustForToken(), null, false, null, true)).thenReturn(tokenResponse);
APIGatewayProxyResponseEvent result = generateApiGatewayRequest(privateKeyJWT, authCode, DOC_APP_CLIENT_ID.getValue(), true);
assertThat(result, hasStatus(200));
assertTrue(result.getBody().contains(refreshToken.getValue()));
assertTrue(result.getBody().contains(accessToken.getValue()));
}
Aggregations