use of com.nimbusds.oauth2.sdk.token.Tokens in project obiba-commons by obiba.
the class OIDCCallbackFilter method validate.
private OIDCCredentials validate(J2EContext context, OIDCConfiguration config, AuthenticationSuccessResponse authResponse) {
AuthorizationCode code = authResponse.getAuthorizationCode();
ClientAuthentication clientAuthentication = new ClientSecretBasic(new ClientID(config.getClientId()), new Secret(config.getSecret()));
try {
// Token request
final TokenRequest request = new TokenRequest(config.findProviderMetaData().getTokenEndpointURI(), clientAuthentication, new AuthorizationCodeGrant(code, new URI(callbackURL + config.getName())));
HTTPRequest tokenHttpRequest = request.toHTTPRequest();
tokenHttpRequest.setConnectTimeout(config.getConnectTimeout());
tokenHttpRequest.setReadTimeout(config.getReadTimeout());
final HTTPResponse httpResponse = tokenHttpRequest.send();
log.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse);
if (response instanceof TokenErrorResponse) {
String error = ((TokenErrorResponse) response).getErrorObject().toJSONObject().toString();
OIDCSession session = oidcSessionManager.getSession(context.getClientId());
onAuthenticationError(session, error, context.getResponse());
throw new OIDCSessionException("Bad token response, error=" + error, session);
}
log.debug("Token response successful");
final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response;
final OIDCTokens oidcTokens = tokenSuccessResponse.getOIDCTokens();
if (config.isUseNonce()) {
OIDCTokenValidator validator = new OIDCTokenValidator(config);
OIDCSession session = oidcSessionManager.getSession(context.getClientId());
IDTokenClaimsSet claimsSet = validator.validate(oidcTokens.getIDToken(), session.getNonce());
if (claimsSet == null) {
onAuthenticationError(session, "ID token cannot be validated", context.getResponse());
throw new OIDCSessionException("ID token cannot be validated", session);
}
}
// save tokens in credentials
OIDCCredentials credentials = new OIDCCredentials();
credentials.setAuthorizationCode(authResponse.getAuthorizationCode());
credentials.setAccessToken(oidcTokens.getAccessToken());
credentials.setRefreshToken(oidcTokens.getRefreshToken());
credentials.setIdToken(oidcTokens.getIDToken());
return credentials;
} catch (Exception e) {
throw new OIDCException(e);
}
}
use of com.nimbusds.oauth2.sdk.token.Tokens in project di-authentication-api by alphagov.
the class TokenHandler method handleRequest.
@Override
public APIGatewayProxyResponseEvent handleRequest(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());
String clientID = requestBody.get("client_id");
ClientRegistry client;
try {
client = clientService.getClient(clientID).orElseThrow();
} catch (NoSuchElementException e) {
LOG.warn("Client not found in Client Registry with Client ID {}", clientID);
return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_CLIENT.toJSONObject().toJSONString());
}
String baseUrl = configurationService.getBaseURL().orElseThrow(() -> {
LOG.error("Application was not configured with baseURL");
// exceptions
return new RuntimeException("Application was not configured with baseURL");
});
String tokenUrl = buildURI(baseUrl, TOKEN_PATH).toString();
Optional<ErrorObject> invalidPrivateKeyJwtError = 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 processRefreshTokenRequest(requestBody, client.getScopes(), new RefreshToken(requestBody.get("refresh_token")));
}
AuthCodeExchangeData authCodeExchangeData;
try {
authCodeExchangeData = 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());
}
ClientSession clientSession = clientSessionService.getClientSession(authCodeExchangeData.getClientSessionId());
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));
}
if (!authRequest.getRedirectionURI().toString().equals(requestBody.get("redirect_uri"))) {
LOG.warn("Redirect URI for auth request ({}) does not match redirect URI for request body ({})", authRequest.getRedirectionURI(), requestBody.get("redirect_uri"));
return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_GRANT.toJSONObject().toJSONString());
}
UserProfile userProfile = dynamoService.getUserProfileByEmail(authCodeExchangeData.getEmail());
Subject publicSubject = ClientSubjectHelper.getSubject(userProfile, client, dynamoService);
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 tokenResponse = tokenService.generateTokenResponse(clientID, new Subject(userProfile.getSubjectID()), authRequest.getScope(), additionalTokenClaims, publicSubject, vot, userProfile.getClientConsent(), client.isConsentRequired(), claimsRequest);
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.oauth2.sdk.token.Tokens in project di-authentication-api by alphagov.
the class IPVCallbackHandlerTest method getApiGatewayProxyRequestEvent.
private APIGatewayProxyRequestEvent getApiGatewayProxyRequestEvent(UserInfo userIdentityUserInfo) {
var successfulTokenResponse = new AccessTokenResponse(new Tokens(new BearerAccessToken(), null));
var tokenRequest = mock(TokenRequest.class);
Map<String, String> responseHeaders = new HashMap<>();
responseHeaders.put("code", AUTH_CODE.getValue());
responseHeaders.put("state", STATE.getValue());
when(dynamoClientService.getClient(CLIENT_ID.getValue())).thenReturn(Optional.of(clientRegistry));
when(responseService.validateResponse(responseHeaders, SESSION_ID)).thenReturn(Optional.empty());
when(dynamoService.getUserProfileFromEmail(TEST_EMAIL_ADDRESS)).thenReturn(Optional.of(userProfile));
when(dynamoService.getOrGenerateSalt(userProfile)).thenReturn(salt);
when(ipvTokenService.constructTokenRequest(AUTH_CODE.getValue())).thenReturn(tokenRequest);
when(ipvTokenService.sendTokenRequest(tokenRequest)).thenReturn(successfulTokenResponse);
when(ipvTokenService.sendIpvUserIdentityRequest(ArgumentMatchers.any())).thenReturn(userIdentityUserInfo);
var event = new APIGatewayProxyRequestEvent();
event.setQueryStringParameters(responseHeaders);
event.setHeaders(Map.of(COOKIE, buildCookieString()));
return event;
}
Aggregations