use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.
the class LogoutIntegrationTest method generateAuthRequest.
private AuthenticationRequest generateAuthRequest(Nonce nonce) {
ResponseType responseType = new ResponseType(ResponseType.Value.CODE);
State state = new State();
Scope scope = new Scope();
scope.add(OIDCScopeValue.OPENID);
return new AuthenticationRequest.Builder(responseType, scope, new ClientID("test-client"), URI.create("http://localhost:8080/redirect")).state(state).nonce(nonce).build();
}
use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.
the class TokenIntegrationTest method generateAuthRequest.
private AuthenticationRequest generateAuthRequest(Scope scope, Optional<String> vtr, Optional<OIDCClaimsRequest> claimsRequest) {
ResponseType responseType = new ResponseType(ResponseType.Value.CODE);
State state = new State();
Nonce nonce = new Nonce();
AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(responseType, scope, new ClientID(CLIENT_ID), URI.create("http://localhost/redirect")).state(state).nonce(nonce);
claimsRequest.ifPresent(builder::claims);
vtr.ifPresent(v -> builder.customParameter("vtr", v));
return builder.build();
}
use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.
the class TokenHandler method tokenRequestHandler.
public APIGatewayProxyResponseEvent tokenRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
return isWarming(input).orElseGet(() -> {
LOG.info("Token request received");
Optional<ErrorObject> invalidRequestParamError = tokenService.validateTokenRequestParams(input.getBody());
if (invalidRequestParamError.isPresent()) {
LOG.warn("Invalid Token Request. ErrorCode: {}. ErrorDescription: {}", invalidRequestParamError.get().getCode(), invalidRequestParamError.get().getDescription());
return generateApiGatewayProxyResponse(400, invalidRequestParamError.get().toJSONObject().toJSONString());
}
Map<String, String> requestBody = parseRequestBody(input.getBody());
addAnnotation("grant_type", requestBody.get("grant_type"));
String clientID;
ClientRegistry client;
try {
clientID = tokenService.getClientIDFromPrivateKeyJWT(input.getBody()).orElseThrow();
attachLogFieldToLogs(CLIENT_ID, clientID);
addAnnotation("client_id", clientID);
client = clientService.getClient(clientID).orElseThrow();
} catch (NoSuchElementException e) {
LOG.warn("Invalid client or client not found in Client Registry");
return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_CLIENT.toJSONObject().toJSONString());
}
String baseUrl = configurationService.getOidcApiBaseURL().orElseThrow(() -> {
LOG.error("Application was not configured with baseURL");
return new RuntimeException("Application was not configured with baseURL");
});
String tokenUrl = buildURI(baseUrl, TOKEN_PATH).toString();
Optional<ErrorObject> invalidPrivateKeyJwtError = segmentedFunctionCall("validatePrivateKeyJWT", () -> tokenService.validatePrivateKeyJWT(input.getBody(), client.getPublicKey(), tokenUrl, clientID));
if (invalidPrivateKeyJwtError.isPresent()) {
LOG.warn("Private Key JWT is not valid for Client ID: {}", clientID);
return generateApiGatewayProxyResponse(400, invalidPrivateKeyJwtError.get().toJSONObject().toJSONString());
}
if (requestBody.get("grant_type").equals(GrantType.REFRESH_TOKEN.getValue())) {
LOG.info("Processing refresh token request");
return segmentedFunctionCall("processRefreshTokenRequest", () -> processRefreshTokenRequest(requestBody, client.getScopes(), new RefreshToken(requestBody.get("refresh_token")), clientID));
}
AuthCodeExchangeData authCodeExchangeData;
try {
authCodeExchangeData = segmentedFunctionCall("authorisationCodeService", () -> authorisationCodeService.getExchangeDataForCode(requestBody.get("code")).orElseThrow());
} catch (NoSuchElementException e) {
LOG.warn("Could not retrieve client session ID from code", e);
return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_GRANT.toJSONObject().toJSONString());
}
updateAttachedLogFieldToLogs(CLIENT_SESSION_ID, authCodeExchangeData.getClientSessionId());
ClientSession clientSession = authCodeExchangeData.getClientSession();
AuthenticationRequest authRequest;
try {
authRequest = AuthenticationRequest.parse(clientSession.getAuthRequestParams());
} catch (ParseException e) {
LOG.warn("Could not parse authentication request from client session", e);
throw new RuntimeException(format("Unable to parse Auth Request\n Auth Request Params: %s \n Exception: %s", clientSession.getAuthRequestParams(), e));
}
var authRequestRedirectURI = isDocCheckingAppUserWithSubjectId(clientSession) ? getRequestObjectClaim(authRequest, "redirect_uri", String.class) : authRequest.getRedirectionURI().toString();
if (!authRequestRedirectURI.equals(requestBody.get("redirect_uri"))) {
LOG.warn("Redirect URI for auth request ({}) does not match redirect URI for request body ({})", authRequestRedirectURI, requestBody.get("redirect_uri"));
return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_GRANT.toJSONObject().toJSONString());
}
Map<String, Object> additionalTokenClaims = new HashMap<>();
if (authRequest.getNonce() != null) {
additionalTokenClaims.put("nonce", authRequest.getNonce());
}
String vot = clientSession.getEffectiveVectorOfTrust().retrieveVectorOfTrustForToken();
OIDCClaimsRequest claimsRequest = null;
if (Objects.nonNull(clientSession.getEffectiveVectorOfTrust().getLevelOfConfidence()) && Objects.nonNull(authRequest.getOIDCClaims())) {
claimsRequest = authRequest.getOIDCClaims();
}
var isConsentRequired = client.isConsentRequired() && !clientSession.getEffectiveVectorOfTrust().containsLevelOfConfidence();
final OIDCClaimsRequest finalClaimsRequest = claimsRequest;
OIDCTokenResponse tokenResponse;
if (isDocCheckingAppUserWithSubjectId(clientSession)) {
LOG.info("Doc Checking App User with SubjectId: true");
Scope scope = new Scope(getRequestObjectScopeClaim(authRequest));
tokenResponse = segmentedFunctionCall("generateTokenResponse", () -> tokenService.generateTokenResponse(clientID, clientSession.getDocAppSubjectId(), scope, additionalTokenClaims, clientSession.getDocAppSubjectId(), vot, null, false, finalClaimsRequest, true));
} else {
UserProfile userProfile = dynamoService.getUserProfileByEmail(authCodeExchangeData.getEmail());
Subject subject = ClientSubjectHelper.getSubject(userProfile, client, dynamoService);
tokenResponse = segmentedFunctionCall("generateTokenResponse", () -> tokenService.generateTokenResponse(clientID, new Subject(userProfile.getSubjectID()), authRequest.getScope(), additionalTokenClaims, subject, vot, userProfile.getClientConsent(), isConsentRequired, finalClaimsRequest, false));
}
clientSessionService.saveClientSession(authCodeExchangeData.getClientSessionId(), clientSession.setIdTokenHint(tokenResponse.getOIDCTokens().getIDToken().serialize()));
LOG.info("Successfully generated tokens");
return generateApiGatewayProxyResponse(200, tokenResponse.toJSONObject().toJSONString());
});
}
use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.
the class AuthCodeHandlerTest method generateValidSessionAndAuthRequest.
private AuthenticationRequest generateValidSessionAndAuthRequest(CredentialTrustLevel requestedLevel, boolean docAppJourney) throws JOSEException {
AuthenticationRequest authRequest;
if (docAppJourney) {
authRequest = generateRequestObjectAuthRequest();
} else {
ResponseType responseType = new ResponseType(ResponseType.Value.CODE);
Scope scope = new Scope();
Nonce nonce = new Nonce();
scope.add(OIDCScopeValue.OPENID);
authRequest = new AuthenticationRequest.Builder(responseType, scope, CLIENT_ID, REDIRECT_URI).state(new State()).nonce(nonce).build();
}
generateValidSession(authRequest.toParameters(), requestedLevel, docAppJourney);
return authRequest;
}
use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.
the class AuthCodeHandlerTest method shouldGenerateSuccessfulAuthResponseAndUpliftAsNecessary.
@ParameterizedTest
@MethodSource("upliftTestParameters")
void shouldGenerateSuccessfulAuthResponseAndUpliftAsNecessary(CredentialTrustLevel initialLevel, CredentialTrustLevel requestedLevel, CredentialTrustLevel finalLevel, boolean docAppJourney) throws ClientNotFoundException, URISyntaxException, Json.JsonException, JOSEException {
AuthorizationCode authorizationCode = new AuthorizationCode();
AuthenticationRequest authRequest = generateValidSessionAndAuthRequest(requestedLevel, docAppJourney);
session.setCurrentCredentialStrength(initialLevel).setNewAccount(NEW);
AuthenticationSuccessResponse authSuccessResponse = new AuthenticationSuccessResponse(authRequest.getRedirectionURI(), authorizationCode, null, null, authRequest.getState(), null, authRequest.getResponseMode());
when(authorizationService.isClientRedirectUriValid(eq(CLIENT_ID), eq(REDIRECT_URI))).thenReturn(true);
when(authorisationCodeService.generateAuthorisationCode(CLIENT_SESSION_ID, EMAIL, clientSession)).thenReturn(authorizationCode);
when(authorizationService.generateSuccessfulAuthResponse(any(AuthenticationRequest.class), any(AuthorizationCode.class), any(URI.class), any(State.class))).thenReturn(authSuccessResponse);
APIGatewayProxyResponseEvent response = generateApiRequest();
assertThat(response, hasStatus(200));
AuthCodeResponse authCodeResponse = objectMapper.readValue(response.getBody(), AuthCodeResponse.class);
assertThat(authCodeResponse.getLocation(), equalTo(authSuccessResponse.toURI().toString()));
assertThat(session.getCurrentCredentialStrength(), equalTo(finalLevel));
assertThat(session.isAuthenticated(), not(equalTo(docAppJourney)));
verify(sessionService, times(docAppJourney ? 0 : 1)).save(session);
verify(auditService).submitAuditEvent(OidcAuditableEvent.AUTH_CODE_ISSUED, "aws-session-id", SESSION_ID, CLIENT_ID.getValue(), AuditService.UNKNOWN, EMAIL, "123.123.123.123", AuditService.UNKNOWN, PERSISTENT_SESSION_ID);
verify(cloudwatchMetricsService).incrementCounter("SignIn", Map.of("Account", "NEW", "Environment", "unit-test", "Client", CLIENT_ID.getValue()));
}
Aggregations