Search in sources :

Example 1 with GrantType

use of com.nimbusds.oauth2.sdk.GrantType in project ddf by codice.

the class OAuthSecurityImpl method getValidToken.

/**
 * Attempts to get an unexpired access token from the token storage or by making a request to the
 * OAuth provider.
 *
 * @param id The ID used when retrieving tokens from the token storage
 * @param sourceId The ID of the source using OAuth needed to get the correct tokens
 * @param clientId The client ID registered with the OAuth provider
 * @param clientSecret The client secret registered with the OAuth provider
 * @param discoveryUrl The discovery URL of the OAuth provider
 * @param grantType The grant type used if a request is sent to get a new token
 * @param queryParameters Parameters used if a request is sent to get a new token
 * @return an access token or null if all means of getting one fail
 */
private String getValidToken(String id, String sourceId, String clientId, String clientSecret, String discoveryUrl, String grantType, Map<String, String> queryParameters) {
    TokenEntry tokenEntry = tokenStorage.read(id, sourceId);
    if (tokenEntry != null && discoveryUrl.equalsIgnoreCase(tokenEntry.getDiscoveryUrl()) && !isExpired(tokenEntry.getAccessToken())) {
        return tokenEntry.getAccessToken();
    }
    OIDCProviderMetadata metadata;
    try {
        metadata = OIDCProviderMetadata.parse(resourceRetriever.retrieveResource(new URL(discoveryUrl)).getContent());
    } catch (IOException | ParseException e) {
        LOGGER.error("Unable to retrieve OAuth provider's metadata.", e);
        return null;
    }
    if (tokenEntry != null && discoveryUrl.equalsIgnoreCase(tokenEntry.getDiscoveryUrl()) && isExpired(tokenEntry.getAccessToken()) && !isExpired(tokenEntry.getRefreshToken())) {
        // refresh token
        return refreshToken(id, sourceId, clientId, clientSecret, discoveryUrl, tokenEntry.getRefreshToken(), metadata);
    }
    // Make a call to get a token
    String encodedClientIdSecret = Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes(UTF_8));
    return getNewAccessToken(id, sourceId, encodedClientIdSecret, discoveryUrl, grantType, queryParameters, metadata);
}
Also used : TokenEntry(org.codice.ddf.security.token.storage.api.TokenInformation.TokenEntry) OIDCProviderMetadata(com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata) IOException(java.io.IOException) ParseException(com.nimbusds.oauth2.sdk.ParseException) URL(java.net.URL)

Example 2 with GrantType

use of com.nimbusds.oauth2.sdk.GrantType in project ddf by codice.

the class OAuthSecurityImpl method getNewAccessToken.

/**
 * Gets an access token from the configured OAuth provider, saves it to the token storage and
 * returns it
 *
 * @param id The ID to use when storing tokens
 * @param sourceId The ID of the source using OAuth to use when storing tokens
 * @param encodedClientIdSecret The base 64 encoded clientId:secret
 * @param discoveryUrl The URL where the Oauth provider's metadata is hosted
 * @param grantType The OAuth grand type to use
 * @param queryParameters Query parameters to send
 * @return a client access token or null if one could not be returned
 */
private String getNewAccessToken(String id, String sourceId, String encodedClientIdSecret, String discoveryUrl, String grantType, Map<String, String> queryParameters, OIDCProviderMetadata metadata) {
    WebClient webClient = createWebClient(metadata.getTokenEndpointURI());
    webClient.header(AUTHORIZATION, BASIC + encodedClientIdSecret);
    webClient.accept(APPLICATION_JSON);
    Form formParam = new Form(GRANT_TYPE, grantType);
    formParam.param(SCOPE, OPENID_SCOPE);
    queryParameters.forEach(formParam::param);
    javax.ws.rs.core.Response response = webClient.form(formParam);
    String body;
    try {
        body = IOUtils.toString((InputStream) response.getEntity(), UTF_8);
    } catch (IOException e) {
        LOGGER.debug("Unable to retrieve system access token.", e);
        return null;
    }
    if (response.getStatus() != HttpStatus.SC_OK) {
        LOGGER.debug("Unable to retrieve system access token. {}", body);
        if (LOGGER.isTraceEnabled()) {
            sanitizeFormParameters(formParam);
            LOGGER.trace("Unable to retrieve system access token. Headers: {}, Request: {}, Status: {}, Response: {}", webClient.getHeaders(), formParam.asMap(), response.getStatus(), body);
        }
        return null;
    }
    Map<String, String> map = GSON.fromJson(body, MAP_STRING_TO_OBJECT_TYPE);
    String idToken = map.get(ID_TOKEN);
    String accessToken = map.get(ACCESS_TOKEN);
    String refreshToken = map.get(REFRESH_TOKEN);
    JWT jwt = null;
    try {
        if (idToken != null) {
            jwt = SignedJWT.parse(idToken);
        }
    } catch (java.text.ParseException e) {
        LOGGER.debug("Error parsing ID token.", e);
    }
    try {
        OidcTokenValidator.validateAccessToken(new BearerAccessToken(accessToken), jwt, resourceRetriever, metadata, null);
    } catch (OidcValidationException e) {
        LOGGER.warn("Error validating system access token.", e);
        return null;
    }
    LOGGER.debug("Successfully retrieved system access token.");
    int status = tokenStorage.create(id, sourceId, accessToken, refreshToken, discoveryUrl);
    if (status != SC_OK) {
        LOGGER.debug("Error storing user token.");
    }
    return accessToken;
}
Also used : Form(javax.ws.rs.core.Form) InputStream(java.io.InputStream) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) IOException(java.io.IOException) WebClient(org.apache.cxf.jaxrs.client.WebClient) OidcValidationException(org.codice.ddf.security.oidc.validator.OidcValidationException) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken)

Example 3 with GrantType

use of com.nimbusds.oauth2.sdk.GrantType in project Kustvakt by KorAP.

the class OpenIdTokenService method requestAccessToken.

public AccessTokenResponse requestAccessToken(TokenRequest tokenRequest) throws KustvaktException {
    AuthorizationGrant grant = tokenRequest.getAuthorizationGrant();
    GrantType grantType = grant.getType();
    ClientAuthentication clientAuthentication = tokenRequest.getClientAuthentication();
    ClientID clientId = tokenRequest.getClientID();
    if (grantType.equals(GrantType.AUTHORIZATION_CODE)) {
        return requestAccessTokenWithAuthorizationCode(grant, clientAuthentication, clientId);
    } else if (grantType.equals(GrantType.PASSWORD)) {
        ResourceOwnerPasswordCredentialsGrant passwordGrant = (ResourceOwnerPasswordCredentialsGrant) grant;
        return requestAccessTokenWithPassword(passwordGrant.getUsername(), passwordGrant.getPassword().getValue(), tokenRequest.getScope(), clientAuthentication, clientId);
    } else if (grantType.equals(GrantType.CLIENT_CREDENTIALS)) {
    } else {
        throw new KustvaktException(StatusCodes.UNSUPPORTED_GRANT_TYPE, grantType + " is not supported.", OAuth2Error.UNSUPPORTED_GRANT_TYPE);
    }
    return null;
}
Also used : KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) ResourceOwnerPasswordCredentialsGrant(com.nimbusds.oauth2.sdk.ResourceOwnerPasswordCredentialsGrant) GrantType(com.nimbusds.oauth2.sdk.GrantType) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication)

Aggregations

IOException (java.io.IOException)2 JWT (com.nimbusds.jwt.JWT)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 AuthorizationGrant (com.nimbusds.oauth2.sdk.AuthorizationGrant)1 GrantType (com.nimbusds.oauth2.sdk.GrantType)1 ParseException (com.nimbusds.oauth2.sdk.ParseException)1 ResourceOwnerPasswordCredentialsGrant (com.nimbusds.oauth2.sdk.ResourceOwnerPasswordCredentialsGrant)1 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)1 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)1 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)1 OIDCProviderMetadata (com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata)1 KustvaktException (de.ids_mannheim.korap.exceptions.KustvaktException)1 InputStream (java.io.InputStream)1 URL (java.net.URL)1 Form (javax.ws.rs.core.Form)1 WebClient (org.apache.cxf.jaxrs.client.WebClient)1 OidcValidationException (org.codice.ddf.security.oidc.validator.OidcValidationException)1 TokenEntry (org.codice.ddf.security.token.storage.api.TokenInformation.TokenEntry)1