Search in sources :

Example 11 with Tokens

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());
}
Also used : RefreshTokenStore(uk.gov.di.authentication.shared.entity.RefreshTokenStore) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) SignedJWT(com.nimbusds.jwt.SignedJWT) Subject(com.nimbusds.oauth2.sdk.id.Subject) Context(com.amazonaws.services.lambda.runtime.Context) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) NoSuchElementException(java.util.NoSuchElementException)

Example 12 with Tokens

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()));
}
Also used : AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) HashMap(java.util.HashMap) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Matchers.containsString(org.hamcrest.Matchers.containsString) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) AccessTokenResponse(com.nimbusds.oauth2.sdk.AccessTokenResponse) URI(java.net.URI) Tokens(com.nimbusds.oauth2.sdk.token.Tokens) URIBuilder(org.apache.http.client.utils.URIBuilder) Test(org.junit.jupiter.api.Test)

Example 13 with Tokens

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);
        }
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens)

Example 14 with Tokens

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();
    }
}
Also used : IOException(java.io.IOException) ParseException(com.nimbusds.oauth2.sdk.ParseException) URI(java.net.URI) Tokens(com.nimbusds.oauth2.sdk.token.Tokens) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 15 with Tokens

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);
}
Also used : STATE(org.codice.ddf.security.token.storage.api.TokenStorage.STATE) Arrays(java.util.Arrays) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) RefreshTokenGrant(org.apache.cxf.rs.security.oauth2.grants.refresh.RefreshTokenGrant) LoggerFactory(org.slf4j.LoggerFactory) DefaultResourceRetriever(com.nimbusds.jose.util.DefaultResourceRetriever) Session(org.apache.shiro.session.Session) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) GsonBuilder(com.google.gson.GsonBuilder) NO_AUTH(ddf.catalog.plugin.OAuthPluginException.ErrorType.NO_AUTH) OAuthClientUtils(org.apache.cxf.rs.security.oauth2.client.OAuthClientUtils) OAuthFederatedSource(ddf.catalog.source.OAuthFederatedSource) EXPIRES_AT(org.codice.ddf.security.token.storage.api.TokenStorage.EXPIRES_AT) Gson(com.google.gson.Gson) OidcTokenValidator(org.codice.ddf.security.oidc.validator.OidcTokenValidator) Map(java.util.Map) Bundle(org.osgi.framework.Bundle) TokenInformation(org.codice.ddf.security.token.storage.api.TokenInformation) ServiceReference(org.osgi.framework.ServiceReference) Consumer(org.apache.cxf.rs.security.oauth2.client.Consumer) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) OAuthPluginException(ddf.catalog.plugin.OAuthPluginException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) URIBuilder(org.apache.http.client.utils.URIBuilder) Collection(java.util.Collection) UUID(java.util.UUID) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) BundleContext(org.osgi.framework.BundleContext) Base64(java.util.Base64) List(java.util.List) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) HashMap(java.util.HashMap) TokenEntry(org.codice.ddf.security.token.storage.api.TokenInformation.TokenEntry) SECRET(org.codice.ddf.security.token.storage.api.TokenStorage.SECRET) SOURCE_ID(org.codice.ddf.security.token.storage.api.TokenStorage.SOURCE_ID) Source(ddf.catalog.source.Source) DISCOVERY_URL(org.codice.ddf.security.token.storage.api.TokenStorage.DISCOVERY_URL) QueryRequest(ddf.catalog.operation.QueryRequest) AUTH_SOURCE(ddf.catalog.plugin.OAuthPluginException.ErrorType.AUTH_SOURCE) ParseException(com.nimbusds.oauth2.sdk.ParseException) CLIENT_ID(org.codice.ddf.security.token.storage.api.TokenStorage.CLIENT_ID) GsonTypeAdapters(org.codice.gsonsupport.GsonTypeAdapters) PreFederatedQueryPlugin(ddf.catalog.plugin.PreFederatedQueryPlugin) Logger(org.slf4j.Logger) SystemBaseUrl(org.codice.ddf.configuration.SystemBaseUrl) OIDCProviderMetadata(com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata) MalformedURLException(java.net.MalformedURLException) WebClient(org.apache.cxf.jaxrs.client.WebClient) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Scope(com.nimbusds.oauth2.sdk.Scope) StopProcessingException(ddf.catalog.plugin.StopProcessingException) Subject(ddf.security.Subject) IOException(java.io.IOException) SECURITY_SUBJECT(ddf.security.SecurityConstants.SECURITY_SUBJECT) OidcValidationException(org.codice.ddf.security.oidc.validator.OidcValidationException) MAP_STRING_TO_OBJECT_TYPE(org.codice.gsonsupport.GsonTypeAdapters.MAP_STRING_TO_OBJECT_TYPE) ResourceRetriever(com.nimbusds.jose.util.ResourceRetriever) SC_OK(org.apache.http.HttpStatus.SC_OK) ChronoUnit(java.time.temporal.ChronoUnit) TokenStorage(org.codice.ddf.security.token.storage.api.TokenStorage) VisibleForTesting(com.google.common.annotations.VisibleForTesting) AccessTokenGrant(org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant) TypelessAccessToken(com.nimbusds.oauth2.sdk.token.TypelessAccessToken) FrameworkUtil(org.osgi.framework.FrameworkUtil) TokenEntry(org.codice.ddf.security.token.storage.api.TokenInformation.TokenEntry) OAuthPluginException(ddf.catalog.plugin.OAuthPluginException) TokenEntry(org.codice.ddf.security.token.storage.api.TokenInformation.TokenEntry) HashMap(java.util.HashMap) TokenInformation(org.codice.ddf.security.token.storage.api.TokenInformation) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

URI (java.net.URI)18 OIDCTokens (com.nimbusds.openid.connect.sdk.token.OIDCTokens)17 ClientSecretBasic (com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)15 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)15 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)15 TokenResponse (com.nimbusds.oauth2.sdk.TokenResponse)14 TokenRequest (com.nimbusds.oauth2.sdk.TokenRequest)13 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)13 Secret (com.nimbusds.oauth2.sdk.auth.Secret)12 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)12 Tokens (com.nimbusds.oauth2.sdk.token.Tokens)11 TokenErrorResponse (com.nimbusds.oauth2.sdk.TokenErrorResponse)10 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)10 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)10 IOException (java.io.IOException)10 AccessTokenResponse (com.nimbusds.oauth2.sdk.AccessTokenResponse)8 Scope (com.nimbusds.oauth2.sdk.Scope)8 RefreshToken (com.nimbusds.oauth2.sdk.token.RefreshToken)8 HashMap (java.util.HashMap)8 Test (org.testng.annotations.Test)8