Search in sources :

Example 26 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens 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)

Example 27 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens 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 28 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project product-is by wso2.

the class OAuth2IDTokenEncryptionTestCase method testAuthCodeGrantSendGetTokensPost.

@Test(groups = "wso2.is", description = "Send get access token request.", dependsOnMethods = "testAuthCodeGrantSendApprovalPost")
public void testAuthCodeGrantSendGetTokensPost() throws Exception {
    ClientID clientID = new ClientID(consumerKey);
    Secret clientSecret = new Secret(consumerSecret);
    ClientSecretBasic clientSecretBasic = new ClientSecretBasic(clientID, clientSecret);
    URI callbackURI = new URI(CALLBACK_URL);
    AuthorizationCodeGrant authorizationCodeGrant = new AuthorizationCodeGrant(authorizationCode, callbackURI);
    TokenRequest tokenReq = new TokenRequest(new URI(OAuth2Constant.ACCESS_TOKEN_ENDPOINT), clientSecretBasic, authorizationCodeGrant);
    HTTPResponse tokenHTTPResp = tokenReq.toHTTPRequest().send();
    Assert.assertNotNull(tokenHTTPResp, "Access token http response is null.");
    TokenResponse tokenResponse = OIDCTokenResponseParser.parse(tokenHTTPResp);
    Assert.assertNotNull(tokenResponse, "Access token response is null.");
    Assert.assertFalse(tokenResponse instanceof TokenErrorResponse, "Access token response contains errors.");
    OIDCTokenResponse oidcTokenResponse = (OIDCTokenResponse) tokenResponse;
    OIDCTokens oidcTokens = oidcTokenResponse.getOIDCTokens();
    Assert.assertNotNull(oidcTokens, "OIDC Tokens object is null.");
    idToken = oidcTokens.getIDTokenString();
    Assert.assertNotNull(idToken, "ID token is null");
}
Also used : Secret(com.nimbusds.oauth2.sdk.auth.Secret) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) Test(org.testng.annotations.Test)

Example 29 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project product-is by wso2.

the class OIDCAuthzCodeIdTokenValidationTestCase method testAuthCodeGrantSendGetTokensPost.

@Test(groups = "wso2.is", description = "Send get access token request.", dependsOnMethods = "testAuthCodeGrantSendApprovalPost")
public void testAuthCodeGrantSendGetTokensPost() throws Exception {
    ClientID clientID = new ClientID(consumerKey);
    Secret clientSecret = new Secret(consumerSecret);
    ClientSecretBasic clientSecretBasic = new ClientSecretBasic(clientID, clientSecret);
    URI callbackURI = new URI(CALLBACK_URL);
    AuthorizationCodeGrant authorizationCodeGrant = new AuthorizationCodeGrant(authorizationCode, callbackURI);
    TokenRequest tokenReq = new TokenRequest(new URI(OAuth2Constant.ACCESS_TOKEN_ENDPOINT), clientSecretBasic, authorizationCodeGrant);
    HTTPResponse tokenHTTPResp = tokenReq.toHTTPRequest().send();
    Assert.assertNotNull(tokenHTTPResp, "Access token http response is null.");
    TokenResponse tokenResponse = OIDCTokenResponseParser.parse(tokenHTTPResp);
    Assert.assertNotNull(tokenResponse, "Access token response is null.");
    Assert.assertFalse(tokenResponse instanceof TokenErrorResponse, "Access token response contains errors.");
    OIDCTokenResponse oidcTokenResponse = (OIDCTokenResponse) tokenResponse;
    OIDCTokens oidcTokens = oidcTokenResponse.getOIDCTokens();
    Assert.assertNotNull(oidcTokens, "OIDC Tokens object is null.");
    idToken = oidcTokens.getIDTokenString();
    Assert.assertNotNull(idToken, "ID token is null");
    JWTClaimsSet jwtClaimsSet = SignedJWT.parse(idToken).getJWTClaimsSet();
    Assert.assertEquals(jwtClaimsSet.getClaim("nonce"), TEST_NONCE, "Invalid nonce received.");
    Assert.assertEquals(jwtClaimsSet.getSubject(), userId, "Invalid subject received.");
    Assert.assertEquals(jwtClaimsSet.getIssuer(), "https://localhost:9853/oauth2/token", "Invalid issuer received.");
}
Also used : Secret(com.nimbusds.oauth2.sdk.auth.Secret) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) AuthorizationCodeGrant(com.nimbusds.oauth2.sdk.AuthorizationCodeGrant) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) Test(org.testng.annotations.Test) OAuth2ServiceAbstractIntegrationTest(org.wso2.identity.integration.test.oauth2.OAuth2ServiceAbstractIntegrationTest)

Example 30 with Tokens

use of com.nimbusds.oauth2.sdk.token.Tokens in project product-is by wso2.

the class OAuth2ServiceJWTGrantTestCase method testPasswordGrantBasedSelfContainedAccessTokenGeneration.

@Test(description = "This test case tests the JWT self contained access token generation using password grant " + "type.")
public void testPasswordGrantBasedSelfContainedAccessTokenGeneration() throws IOException, URISyntaxException, ParseException, java.text.ParseException, ClaimMetadataManagementServiceClaimMetadataException {
    Secret password = new Secret(JWT_USER);
    AuthorizationGrant passwordGrant = new ResourceOwnerPasswordCredentialsGrant(JWT_USER, password);
    ClientID clientID = new ClientID(consumerKey);
    Secret clientSecret = new Secret(consumerSecret);
    ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);
    URI tokenEndpoint = new URI(OAuth2Constant.ACCESS_TOKEN_ENDPOINT);
    TokenRequest request = new TokenRequest(tokenEndpoint, clientAuth, passwordGrant, new Scope(OAuth2Constant.OAUTH2_SCOPE_OPENID + " " + OAuth2Constant.OAUTH2_SCOPE_EMAIL));
    HTTPResponse tokenHTTPResp = request.toHTTPRequest().send();
    Assert.assertNotNull(tokenHTTPResp, "JWT access token http response is null.");
    TokenResponse tokenResponse = OIDCTokenResponseParser.parse(tokenHTTPResp);
    Assert.assertNotNull(tokenResponse, "Token response of JWT access token response is null.");
    Assert.assertFalse(tokenResponse instanceof TokenErrorResponse, "JWT access token response contains errors.");
    OIDCTokenResponse oidcTokenResponse = (OIDCTokenResponse) tokenResponse;
    OIDCTokens oidcTokens = oidcTokenResponse.getOIDCTokens();
    Assert.assertNotNull(oidcTokens, "OIDC Tokens object is null in JWT token");
    jwtAssertion = oidcTokens.getIDTokenString();
    alias = oidcTokens.getIDToken().getJWTClaimsSet().getAudience().get(0);
    issuer = oidcTokens.getIDToken().getJWTClaimsSet().getIssuer();
    Assert.assertEquals(oidcTokens.getIDToken().getJWTClaimsSet().getClaim(COUNTRY_NEW_OIDC_CLAIM), COUNTRY_CLAIM_VALUE, "Requested user claims is not returned back in self contained access token based" + " on password claim.");
    Assert.assertEquals(oidcTokens.getIDToken().getJWTClaimsSet().getClaim(EMAIL_OIDC_CLAIM), EMAIL_CLAIM_VALUE, "Requested user claims is not returned back in self contained access token based on password " + "claim.");
    String GIVEN_NAME_OIDC_CLAIM = "given_name";
    Assert.assertNull(oidcTokens.getIDToken().getJWTClaimsSet().getClaim(GIVEN_NAME_OIDC_CLAIM), "Non-requested user claim " + GIVEN_NAME_OIDC_CLAIM + " is not returned back in self contained access " + "token based on password claim");
    Assert.assertNull(oidcTokens.getIDToken().getJWTClaimsSet().getClaim(EMAIL_LOCAL_CLAIM_URI), "User claim " + EMAIL_LOCAL_CLAIM_URI + " is not returned in local claim uri format without being " + "converted to OIDC claim");
}
Also used : HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) ResourceOwnerPasswordCredentialsGrant(com.nimbusds.oauth2.sdk.ResourceOwnerPasswordCredentialsGrant) URI(java.net.URI) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) Secret(com.nimbusds.oauth2.sdk.auth.Secret) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) Scope(com.nimbusds.oauth2.sdk.Scope) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) AuthorizationGrant(com.nimbusds.oauth2.sdk.AuthorizationGrant) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) Test(org.testng.annotations.Test)

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