Search in sources :

Example 1 with AccessTokenGrant

use of org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant in project ddf by codice.

the class OAuthPlugin method refreshTokens.

/**
 * Attempts to refresh the user's access token and saves the new tokens in the token storage
 *
 * @param refreshToken refresh token used to refresh access token
 * @param oauthSource source being queried
 * @throws OAuthPluginException if the access token could not be renewed
 */
private void refreshTokens(String refreshToken, OAuthFederatedSource oauthSource, String sessionId, OIDCProviderMetadata metadata) throws StopProcessingException {
    if (refreshToken == null) {
        throw createNoAuthException(oauthSource, sessionId, metadata, "unable to find the user's refresh token.");
    }
    ClientAccessToken clientAccessToken;
    try {
        LOGGER.debug("Attempting to refresh the user's access token.");
        WebClient webClient = createWebclient(metadata.getTokenEndpointURI().toURL().toString());
        Consumer consumer = new Consumer(oauthSource.getOauthClientId(), oauthSource.getOauthClientSecret());
        AccessTokenGrant accessTokenGrant = new RefreshTokenGrant(refreshToken);
        clientAccessToken = OAuthClientUtils.getAccessToken(webClient, consumer, accessTokenGrant);
    } catch (OAuthServiceException e) {
        String error = e.getError() != null ? e.getError().getError() : "";
        throw createNoAuthException(oauthSource, sessionId, metadata, "failed to refresh access token " + error);
    } catch (MalformedURLException e) {
        throw createNoAuthException(oauthSource, sessionId, metadata, "malformed token endpoint URL. " + e.getMessage());
    }
    // Validate new access token
    try {
        AccessToken accessToken = convertCxfAccessTokenToNimbusdsToken(clientAccessToken);
        OidcTokenValidator.validateAccessToken(accessToken, null, resourceRetriever, metadata, null);
    } catch (OidcValidationException e) {
        throw createNoAuthException(oauthSource, sessionId, metadata, "failed to validate refreshed access token.");
    }
    // Store new tokens
    String newAccessToken = clientAccessToken.getTokenKey();
    String newRefreshToken = clientAccessToken.getRefreshToken();
    int status = tokenStorage.create(sessionId, oauthSource.getId(), newAccessToken, newRefreshToken, oauthSource.getOauthDiscoveryUrl());
    if (status != SC_OK) {
        LOGGER.warn("Error updating the token information.");
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Consumer(org.apache.cxf.rs.security.oauth2.client.Consumer) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) RefreshTokenGrant(org.apache.cxf.rs.security.oauth2.grants.refresh.RefreshTokenGrant) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) TypelessAccessToken(com.nimbusds.oauth2.sdk.token.TypelessAccessToken) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) AccessTokenGrant(org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant) WebClient(org.apache.cxf.jaxrs.client.WebClient) OidcValidationException(org.codice.ddf.security.oidc.validator.OidcValidationException)

Example 2 with AccessTokenGrant

use of org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant in project cxf by apache.

the class OAuthClientUtils method getAccessToken.

/**
 * Obtains the access token from OAuth AccessToken Service
 * using the initialized web client
 * @param accessTokenService the AccessToken client
 * @param consumer {@link Consumer} representing the registered client.
 * @param grant {@link AccessTokenGrant} grant
 * @param extraParams extra parameters
 * @param defaultTokenType default expected token type - some early
 *        well-known OAuth2 services do not return a required token_type parameter
 * @param setAuthorizationHeader if set to true then HTTP Basic scheme
 *           will be used to pass client id and secret, otherwise they will
 *           be passed in the form payload
 * @return {@link ClientAccessToken} access token
 * @throws OAuthServiceException
 */
public static ClientAccessToken getAccessToken(WebClient accessTokenService, Consumer consumer, AccessTokenGrant grant, Map<String, String> extraParams, String defaultTokenType, boolean setAuthorizationHeader) throws OAuthServiceException {
    if (accessTokenService == null) {
        throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
    }
    Form form = new Form(grant.toMap());
    if (extraParams != null) {
        for (Map.Entry<String, String> entry : extraParams.entrySet()) {
            form.param(entry.getKey(), entry.getValue());
        }
    }
    if (consumer != null) {
        boolean secretAvailable = !StringUtils.isEmpty(consumer.getClientSecret());
        if (setAuthorizationHeader && secretAvailable) {
            accessTokenService.replaceHeader(HttpHeaders.AUTHORIZATION, DefaultBasicAuthSupplier.getBasicAuthHeader(consumer.getClientId(), consumer.getClientSecret()));
        } else {
            form.param(OAuthConstants.CLIENT_ID, consumer.getClientId());
            if (secretAvailable) {
                form.param(OAuthConstants.CLIENT_SECRET, consumer.getClientSecret());
            }
        }
    } else {
    // in this case the AccessToken service is expected to find a mapping between
    // the authenticated credentials and the client registration id
    }
    Response response = accessTokenService.form(form);
    final Map<String, String> map;
    try {
        map = response.getMediaType() == null || response.getMediaType().isCompatible(MediaType.APPLICATION_JSON_TYPE) ? new OAuthJSONProvider().readJSONResponse((InputStream) response.getEntity()) : Collections.emptyMap();
    } catch (Exception ex) {
        throw new ResponseProcessingException(response, ex);
    }
    if (200 == response.getStatus()) {
        ClientAccessToken token = fromMapToClientToken(map, defaultTokenType);
        if (token == null) {
            throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
        }
        return token;
    } else if (response.getStatus() >= 400 && map.containsKey(OAuthConstants.ERROR_KEY)) {
        OAuthError error = new OAuthError(map.get(OAuthConstants.ERROR_KEY), map.get(OAuthConstants.ERROR_DESCRIPTION_KEY));
        error.setErrorUri(map.get(OAuthConstants.ERROR_URI_KEY));
        throw new OAuthServiceException(error);
    }
    throw new OAuthServiceException(OAuthConstants.SERVER_ERROR);
}
Also used : OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) Form(javax.ws.rs.core.Form) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) ProcessingException(javax.ws.rs.ProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) Response(javax.ws.rs.core.Response) OAuthError(org.apache.cxf.rs.security.oauth2.common.OAuthError) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) Map(java.util.Map)

Example 3 with AccessTokenGrant

use of org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant in project teiid by teiid.

the class OAuthUtil method oauth20Flow.

private static void oauth20Flow(Scanner in) throws Exception {
    System.out.println("=== OAuth 2.0 Workflow ===");
    System.out.println();
    String clientID = getInput(in, "Enter the Client ID = ");
    String clientSecret = getInput(in, "Enter the Client Secret = ");
    org.apache.cxf.rs.security.oauth2.client.Consumer consumer = new org.apache.cxf.rs.security.oauth2.client.Consumer(clientID, clientSecret);
    String authorizeURL = getInput(in, "Enter the User Authorization URL = ");
    String scope = getInput(in, "Enter scope (hit enter for none) = ", true);
    String callback = getInput(in, "Enter callback URL (default: urn:ietf:wg:oauth:2.0:oob) = ", true);
    if (callback == null) {
        callback = "urn:ietf:wg:oauth:2.0:oob";
    }
    URI authenticateURL = org.apache.cxf.rs.security.oauth2.client.OAuthClientUtils.getAuthorizationURI(authorizeURL, consumer.getKey(), callback, "Auth URL", scope);
    System.out.println("Cut & Paste the URL in a web browser, and Authticate");
    System.out.println("Authorize URL  = " + authenticateURL.toASCIIString());
    System.out.println("");
    String authCode = getInput(in, "Enter Token Secret (Auth Code, Pin) from previous step = ");
    String accessTokenURL = getInput(in, "Enter the Access Token URL = ");
    WebClient client = WebClient.create(accessTokenURL);
    AccessTokenGrant grant = new AuthorizationCodeGrant(authCode, new URI(callback));
    ClientAccessToken clientToken = org.apache.cxf.rs.security.oauth2.client.OAuthClientUtils.getAccessToken(client, consumer, grant, null, false);
    System.out.println("Refresh Token=" + clientToken.getRefreshToken());
    System.out.println("");
    System.out.println("Add the following XML into your standalone-teiid.xml file in security-domains subsystem,\n" + "and configure data source securty to this domain");
    System.out.println("");
    System.out.println("");
    System.out.println(MessageFormat.format(OAUTH2_0_DOMAIN, clientID, clientSecret, clientToken.getRefreshToken(), accessTokenURL));
}
Also used : ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) AccessTokenGrant(org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant) URI(java.net.URI) WebClient(org.apache.cxf.jaxrs.client.WebClient) AuthorizationCodeGrant(org.apache.cxf.rs.security.oauth2.grants.code.AuthorizationCodeGrant)

Example 4 with AccessTokenGrant

use of org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant in project cxf by apache.

the class OAuthClientUtils method getAccessToken.

/**
 * Obtains the access token from OAuth AccessToken Service
 * @param accessTokenServiceUri the AccessToken endpoint address
 * @param consumer {@link Consumer} representing the registered client
 * @param grant {@link AccessTokenGrant} grant
 * @param setAuthorizationHeader if set to true then HTTP Basic scheme
 *           will be used to pass client id and secret, otherwise they will
 *           be passed in the form payload
 * @return {@link ClientAccessToken} access token
 * @throws OAuthServiceException
 */
public static ClientAccessToken getAccessToken(String accessTokenServiceUri, Consumer consumer, AccessTokenGrant grant, boolean setAuthorizationHeader) throws OAuthServiceException {
    OAuthJSONProvider provider = new OAuthJSONProvider();
    WebClient accessTokenService = WebClient.create(accessTokenServiceUri, Collections.singletonList(provider));
    accessTokenService.accept("application/json");
    return getAccessToken(accessTokenService, consumer, grant, setAuthorizationHeader);
}
Also used : OAuthJSONProvider(org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider) WebClient(org.apache.cxf.jaxrs.client.WebClient)

Example 5 with AccessTokenGrant

use of org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant in project ddf by codice.

the class OAuthSecurityImpl method refreshToken.

/**
 * Attempts to refresh an expired access token
 *
 * @param id The ID to use when storing tokens
 * @param sourceId The ID of the source using OAuth to use when storing tokens
 * @param clientId The client ID registered with the OAuth provider
 * @param clientSecret The client secret registered with the OAuth provider
 * @param discoveryUrl The URL where the OAuth provider's metadata is hosted
 * @param refreshToken The unexpired refresh token to use
 * @param metadata The OAuh provider's metadata
 * @return refreshed access token
 */
private String refreshToken(String id, String sourceId, String clientId, String clientSecret, String discoveryUrl, String refreshToken, OIDCProviderMetadata metadata) {
    if (refreshToken == null || isExpired(refreshToken)) {
        LOGGER.debug("Error refreshing access token: unable to find an unexpired refresh token.");
        return null;
    }
    ClientAccessToken clientAccessToken;
    try {
        LOGGER.debug("Attempting to refresh the user's access token.");
        WebClient webClient = createWebClient(metadata.getTokenEndpointURI());
        Consumer consumer = new Consumer(clientId, clientSecret);
        AccessTokenGrant accessTokenGrant = new RefreshTokenGrant(refreshToken);
        clientAccessToken = OAuthClientUtils.getAccessToken(webClient, consumer, accessTokenGrant);
    } catch (OAuthServiceException e) {
        LOGGER.debug("Error refreshing access token.", e);
        return null;
    }
    // Validate new access token
    try {
        AccessToken accessToken = convertCxfAccessTokenToNimbusdsToken(clientAccessToken);
        OidcTokenValidator.validateAccessToken(accessToken, null, resourceRetriever, metadata, null);
    } catch (OidcValidationException e) {
        LOGGER.debug("Error validating access token.");
        return null;
    }
    // Store new tokens
    String newAccessToken = clientAccessToken.getTokenKey();
    String newRefreshToken = clientAccessToken.getRefreshToken();
    int status = tokenStorage.create(id, sourceId, newAccessToken, newRefreshToken, discoveryUrl);
    if (status != SC_OK) {
        LOGGER.warn("Error updating the token information.");
    }
    return newAccessToken;
}
Also used : Consumer(org.apache.cxf.rs.security.oauth2.client.Consumer) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) RefreshTokenGrant(org.apache.cxf.rs.security.oauth2.grants.refresh.RefreshTokenGrant) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) TypelessAccessToken(com.nimbusds.oauth2.sdk.token.TypelessAccessToken) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) AccessTokenGrant(org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant) WebClient(org.apache.cxf.jaxrs.client.WebClient) OidcValidationException(org.codice.ddf.security.oidc.validator.OidcValidationException)

Aggregations

WebClient (org.apache.cxf.jaxrs.client.WebClient)4 ClientAccessToken (org.apache.cxf.rs.security.oauth2.common.ClientAccessToken)4 AccessTokenGrant (org.apache.cxf.rs.security.oauth2.common.AccessTokenGrant)3 OAuthServiceException (org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)3 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)2 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)2 TypelessAccessToken (com.nimbusds.oauth2.sdk.token.TypelessAccessToken)2 Consumer (org.apache.cxf.rs.security.oauth2.client.Consumer)2 RefreshTokenGrant (org.apache.cxf.rs.security.oauth2.grants.refresh.RefreshTokenGrant)2 OAuthJSONProvider (org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider)2 OidcValidationException (org.codice.ddf.security.oidc.validator.OidcValidationException)2 MalformedURLException (java.net.MalformedURLException)1 URI (java.net.URI)1 Map (java.util.Map)1 ProcessingException (javax.ws.rs.ProcessingException)1 ResponseProcessingException (javax.ws.rs.client.ResponseProcessingException)1 Form (javax.ws.rs.core.Form)1 Response (javax.ws.rs.core.Response)1 OAuthError (org.apache.cxf.rs.security.oauth2.common.OAuthError)1 AuthorizationCodeGrant (org.apache.cxf.rs.security.oauth2.grants.code.AuthorizationCodeGrant)1