use of com.nimbusds.oauth2.sdk.token.Tokens in project di-authentication-api by alphagov.
the class TokenHandler method processRefreshTokenRequest.
private APIGatewayProxyResponseEvent processRefreshTokenRequest(Map<String, String> requestBody, List<String> clientScopes, RefreshToken currentRefreshToken) {
boolean refreshTokenSignatureValid = tokenValidationService.validateRefreshTokenSignatureAndExpiry(currentRefreshToken);
if (!refreshTokenSignatureValid) {
return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_GRANT.toJSONObject().toJSONString());
}
Subject publicSubject;
List<String> scopes;
try {
SignedJWT signedJwt = SignedJWT.parse(currentRefreshToken.getValue());
publicSubject = new Subject(signedJwt.getJWTClaimsSet().getSubject());
scopes = (List<String>) signedJwt.getJWTClaimsSet().getClaim("scope");
} catch (java.text.ParseException e) {
LOG.warn("Unable to parse RefreshToken");
return generateApiGatewayProxyResponse(400, new ErrorObject(OAuth2Error.INVALID_GRANT_CODE, "Invalid Refresh token").toJSONObject().toJSONString());
}
boolean areScopesValid = tokenValidationService.validateRefreshTokenScopes(clientScopes, scopes);
if (!areScopesValid) {
return generateApiGatewayProxyResponse(400, OAuth2Error.INVALID_SCOPE.toJSONObject().toJSONString());
}
String clientId = requestBody.get("client_id");
String redisKey = REFRESH_TOKEN_PREFIX + clientId + "." + publicSubject.getValue();
Optional<String> refreshToken = Optional.ofNullable(redisConnectionService.getValue(redisKey));
RefreshTokenStore tokenStore;
try {
tokenStore = new ObjectMapper().readValue(refreshToken.get(), RefreshTokenStore.class);
} catch (JsonProcessingException | NoSuchElementException | IllegalArgumentException e) {
LOG.warn("Refresh token not found with given key");
return generateApiGatewayProxyResponse(400, new ErrorObject(OAuth2Error.INVALID_GRANT_CODE, "Invalid Refresh token").toJSONObject().toJSONString());
}
if (!tokenStore.getRefreshTokens().contains(currentRefreshToken.getValue())) {
LOG.warn("Refresh token store does not contain Refresh token in request");
return generateApiGatewayProxyResponse(400, new ErrorObject(OAuth2Error.INVALID_GRANT_CODE, "Invalid Refresh token").toJSONObject().toJSONString());
}
if (tokenStore.getRefreshTokens().size() > 1) {
LOG.info("Removing Refresh Token from refresh token store");
try {
redisConnectionService.saveWithExpiry(redisKey, new ObjectMapper().writeValueAsString(tokenStore.removeRefreshToken(currentRefreshToken.getValue())), configurationService.getSessionExpiry());
} catch (JsonProcessingException e) {
LOG.error("Unable to serialize refresh token store when updating");
throw new RuntimeException(e);
}
} else {
LOG.info("Deleting refresh token store as no other refresh tokens exist");
redisConnectionService.deleteValue(redisKey);
}
OIDCTokenResponse tokenResponse = tokenService.generateRefreshTokenResponse(clientId, new Subject(tokenStore.getInternalSubjectId()), scopes, publicSubject);
LOG.info("Generating successful RefreshToken response");
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 shouldRedirectToLoginUriForSuccessfulResponse.
@Test
void shouldRedirectToLoginUriForSuccessfulResponse() throws URISyntaxException {
usingValidSession();
usingValidClientSession();
TokenResponse successfulTokenResponse = new AccessTokenResponse(new Tokens(new BearerAccessToken(), null));
TokenRequest 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(generateClientRegistry()));
when(responseService.validateResponse(responseHeaders, SESSION_ID)).thenReturn(Optional.empty());
when(dynamoService.getUserProfileFromEmail(TEST_EMAIL_ADDRESS)).thenReturn(Optional.of(generateUserProfile()));
when(ipvTokenService.constructTokenRequest(AUTH_CODE.getValue())).thenReturn(tokenRequest);
when(ipvTokenService.sendTokenRequest(tokenRequest)).thenReturn(successfulTokenResponse);
when(ipvTokenService.sendIpvInfoRequest(successfulTokenResponse.toSuccessResponse().getTokens().getBearerAccessToken())).thenReturn(SignedCredentialHelper.generateCredential().serialize());
APIGatewayProxyRequestEvent event = new APIGatewayProxyRequestEvent();
event.setQueryStringParameters(responseHeaders);
event.setHeaders(Map.of(COOKIE, buildCookieString()));
APIGatewayProxyResponseEvent response = makeHandlerRequest(event);
assertThat(response, hasStatus(302));
URI redirectUri = new URIBuilder(LOGIN_URL).setPath("auth-code").build();
assertThat(response.getHeaders().get("Location"), equalTo(redirectUri.toString()));
}
use of com.nimbusds.oauth2.sdk.token.Tokens in project pac4j by pac4j.
the class OidcAuthenticator method validate.
@Override
public void validate(final OidcCredentials credentials, final WebContext context) {
final AuthorizationCode code = credentials.getCode();
// if we have a code
if (code != null) {
try {
final String computedCallbackUrl = client.computeFinalCallbackUrl(context);
// Token request
final TokenRequest request = new TokenRequest(configuration.findProviderMetadata().getTokenEndpointURI(), this.clientAuthentication, new AuthorizationCodeGrant(code, new URI(computedCallbackUrl)));
HTTPRequest tokenHttpRequest = request.toHTTPRequest();
tokenHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
tokenHttpRequest.setReadTimeout(configuration.getReadTimeout());
final HTTPResponse httpResponse = tokenHttpRequest.send();
logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse);
if (response instanceof TokenErrorResponse) {
throw new TechnicalException("Bad token response, error=" + ((TokenErrorResponse) response).getErrorObject());
}
logger.debug("Token response successful");
final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response;
// save tokens in credentials
final OIDCTokens oidcTokens = tokenSuccessResponse.getOIDCTokens();
credentials.setAccessToken(oidcTokens.getAccessToken());
credentials.setRefreshToken(oidcTokens.getRefreshToken());
credentials.setIdToken(oidcTokens.getIDToken());
} catch (final URISyntaxException | IOException | ParseException e) {
throw new TechnicalException(e);
}
}
}
use of com.nimbusds.oauth2.sdk.token.Tokens in project timbuctoo by HuygensING.
the class LoginEndPoint method callback.
@GET
@Path("/callback")
public Response callback(@QueryParam("state") UUID loginSession, @QueryParam("code") String code) {
if (!loginSessionRedirects.containsKey(loginSession)) {
return Response.status(417).entity("Login session unknown").build();
}
try {
final Optional<Tokens> userTokens = openIdClient.getUserTokens(code);
final String value = userTokens.isPresent() ? userTokens.get().getBearerAccessToken().getValue() : "no-token";
final URI userUri = UriBuilder.fromUri(loginSessionRedirects.get(loginSession)).queryParam("sessionToken", value).build();
return Response.temporaryRedirect(userUri).build();
} catch (IOException | ParseException e) {
LOG.error("Retrieval of userTokes failed", e);
return Response.serverError().build();
}
}
use of com.nimbusds.oauth2.sdk.token.Tokens in project ddf by codice.
the class OAuthPlugin method findExistingTokens.
/**
* Looks through the user's tokens to see if there are tokens from a different source connected to
* the same OAuth provider. The discovery URLs need to match. If a match is found an authorize
* source exception will be thrown so the user can authorize to query the new source instead of
* logging in.
*/
private void findExistingTokens(OAuthFederatedSource oauthSource, String sessionId, OIDCProviderMetadata metadata) throws StopProcessingException {
TokenInformation tokenInformation = tokenStorage.read(sessionId);
if (tokenInformation == null || !tokenInformation.getDiscoveryUrls().contains(oauthSource.getOauthDiscoveryUrl())) {
return;
}
// Verify that an unexpired token exists
List<TokenInformation.TokenEntry> matchingTokenEntries = tokenInformation.getTokenEntries().entrySet().stream().filter(entry -> !entry.getKey().equals(oauthSource.getId())).filter(entry -> entry.getValue().getDiscoveryUrl().equals(oauthSource.getOauthDiscoveryUrl())).map(Map.Entry::getValue).collect(Collectors.toList());
TokenInformation.TokenEntry tokenEntry = matchingTokenEntries.stream().filter(entry -> entry.getAccessToken() != null).filter(entry -> !isExpired(entry.getAccessToken())).findAny().orElse(null);
if (tokenEntry == null) {
// does one with a valid refresh token exist
tokenEntry = matchingTokenEntries.stream().filter(entry -> entry.getRefreshToken() != null).filter(entry -> !isExpired(entry.getRefreshToken())).findAny().orElse(null);
if (tokenEntry == null) {
return;
}
refreshTokens(tokenEntry.getRefreshToken(), oauthSource, sessionId, metadata);
}
LOGGER.debug("Unable to process query. The user needs to authorize to query the {} source.", oauthSource.getId());
Map<String, String> parameters = new HashMap<>();
parameters.put(SOURCE_ID, oauthSource.getId());
parameters.put(DISCOVERY_URL, oauthSource.getOauthDiscoveryUrl());
throw new OAuthPluginException(oauthSource.getId(), buildUrl(AUTHORIZE_SOURCE_ENDPOINT, parameters), AUTHORIZE_SOURCE_ENDPOINT, parameters, AUTH_SOURCE);
}
Aggregations