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);
}
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;
}
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;
}
Aggregations