Search in sources :

Example 1 with BearerAccessToken

use of com.nimbusds.oauth2.sdk.token.BearerAccessToken in project nifi by apache.

the class StandardOidcIdentityProvider method lookupEmail.

private String lookupEmail(final BearerAccessToken bearerAccessToken) throws IOException {
    try {
        // build the user request
        final UserInfoRequest request = new UserInfoRequest(oidcProviderMetadata.getUserInfoEndpointURI(), bearerAccessToken);
        final HTTPRequest tokenHttpRequest = request.toHTTPRequest();
        tokenHttpRequest.setConnectTimeout(oidcConnectTimeout);
        tokenHttpRequest.setReadTimeout(oidcReadTimeout);
        // send the user request
        final UserInfoResponse response = UserInfoResponse.parse(request.toHTTPRequest().send());
        // interpret the details
        if (response.indicatesSuccess()) {
            final UserInfoSuccessResponse successResponse = (UserInfoSuccessResponse) response;
            final JWTClaimsSet claimsSet;
            if (successResponse.getUserInfo() != null) {
                claimsSet = successResponse.getUserInfo().toJWTClaimsSet();
            } else {
                claimsSet = successResponse.getUserInfoJWT().getJWTClaimsSet();
            }
            final String email = claimsSet.getStringClaim(EMAIL_CLAIM_NAME);
            // ensure we were able to get the user email
            if (StringUtils.isBlank(email)) {
                throw new IllegalStateException("Unable to extract email from the UserInfo token.");
            } else {
                return email;
            }
        } else {
            final UserInfoErrorResponse errorResponse = (UserInfoErrorResponse) response;
            throw new RuntimeException("An error occurred while invoking the UserInfo endpoint: " + errorResponse.getErrorObject().getDescription());
        }
    } catch (final ParseException | java.text.ParseException e) {
        throw new RuntimeException("Unable to parse the response from the UserInfo token request: " + e.getMessage());
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) UserInfoSuccessResponse(com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) UserInfoErrorResponse(com.nimbusds.openid.connect.sdk.UserInfoErrorResponse) UserInfoRequest(com.nimbusds.openid.connect.sdk.UserInfoRequest) ParseException(com.nimbusds.oauth2.sdk.ParseException) UserInfoResponse(com.nimbusds.openid.connect.sdk.UserInfoResponse)

Example 2 with BearerAccessToken

use of com.nimbusds.oauth2.sdk.token.BearerAccessToken in project pac4j by pac4j.

the class OidcProfileCreator method create.

@Override
@SuppressWarnings("unchecked")
public U create(final OidcCredentials credentials, final WebContext context) {
    init();
    final AccessToken accessToken = credentials.getAccessToken();
    // Create profile
    final U profile = getProfileDefinition().newProfile();
    profile.setAccessToken(accessToken);
    final JWT idToken = credentials.getIdToken();
    profile.setIdTokenString(idToken.getParsedString());
    // Check if there is a refresh token
    final RefreshToken refreshToken = credentials.getRefreshToken();
    if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
        profile.setRefreshToken(refreshToken);
        logger.debug("Refresh Token successful retrieved");
    }
    try {
        // check idToken
        final Nonce nonce;
        if (configuration.isUseNonce()) {
            nonce = new Nonce((String) context.getSessionStore().get(context, OidcConfiguration.NONCE_SESSION_ATTRIBUTE));
        } else {
            nonce = null;
        }
        // Check ID Token
        final IDTokenClaimsSet claimsSet = this.idTokenValidator.validate(idToken, nonce);
        assertNotNull("claimsSet", claimsSet);
        profile.setId(ProfileHelper.sanitizeIdentifier(profile, claimsSet.getSubject()));
        // User Info request
        if (configuration.findProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
            final UserInfoRequest userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), (BearerAccessToken) accessToken);
            final HTTPRequest userInfoHttpRequest = userInfoRequest.toHTTPRequest();
            userInfoHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
            userInfoHttpRequest.setReadTimeout(configuration.getReadTimeout());
            final HTTPResponse httpResponse = userInfoHttpRequest.send();
            logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
            final UserInfoResponse userInfoResponse = UserInfoResponse.parse(httpResponse);
            if (userInfoResponse instanceof UserInfoErrorResponse) {
                logger.error("Bad User Info response, error={}", ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
            } else {
                final UserInfoSuccessResponse userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
                final JWTClaimsSet userInfoClaimsSet;
                if (userInfoSuccessResponse.getUserInfo() != null) {
                    userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
                } else {
                    userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
                }
                getProfileDefinition().convertAndAdd(profile, userInfoClaimsSet.getClaims(), null);
            }
        }
        // add attributes of the ID token if they don't already exist
        for (final Map.Entry<String, Object> entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();
            // it's not the subject and this attribute does not already exist, add it
            if (!JwtClaims.SUBJECT.equals(key) && profile.getAttribute(key) == null) {
                getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, key, value);
            }
        }
        return profile;
    } catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
        throw new TechnicalException(e);
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) JWT(com.nimbusds.jwt.JWT) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) IOException(java.io.IOException) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(com.nimbusds.oauth2.sdk.ParseException) Map(java.util.Map) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Example 3 with BearerAccessToken

use of com.nimbusds.oauth2.sdk.token.BearerAccessToken in project pac4j by pac4j.

the class OidcCredentialsTests method testSerialization.

@Test
public void testSerialization() throws ParseException {
    final OidcCredentials credentials = new OidcCredentials();
    credentials.setCode(new AuthorizationCode(VALUE));
    credentials.setAccessToken(new BearerAccessToken(VALUE, 0L, Scope.parse("oidc email")));
    credentials.setRefreshToken(new RefreshToken(VALUE));
    credentials.setIdToken(JWTParser.parse(ID_TOKEN));
    byte[] result = SerializationUtils.serialize(credentials);
    final OidcCredentials credentials2 = SerializationUtils.deserialize(result);
    assertEquals(credentials.getAccessToken(), credentials2.getAccessToken());
    assertEquals(credentials.getRefreshToken(), credentials2.getRefreshToken());
    assertEquals(credentials.getIdToken().getParsedString(), credentials2.getIdToken().getParsedString());
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Test(org.junit.Test)

Example 4 with BearerAccessToken

use of com.nimbusds.oauth2.sdk.token.BearerAccessToken in project pac4j by pac4j.

the class OidcProfileTests method testClearProfile.

@Test
public void testClearProfile() {
    OidcProfile profile = new OidcProfile();
    profile.setAccessToken(new BearerAccessToken());
    profile.setIdTokenString(ID);
    profile.setRefreshToken(new RefreshToken(REFRESH_TOKEN));
    profile.clearSensitiveData();
    assertNull(profile.getAccessToken());
    assertNull(profile.getIdTokenString());
}
Also used : RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Test(org.junit.Test)

Example 5 with BearerAccessToken

use of com.nimbusds.oauth2.sdk.token.BearerAccessToken in project pac4j by pac4j.

the class OidcProfileTests method testReadWriteObjectNullAccessToken.

/**
 * Test that serialization and deserialization of the OidcProfile work when the BearerAccessToken is null.
 */
@Test
public void testReadWriteObjectNullAccessToken() {
    OidcProfile profile = new OidcProfile();
    profile.setIdTokenString(ID_TOKEN);
    profile.setRefreshToken(new RefreshToken(REFRESH_TOKEN));
    byte[] result = SerializationUtils.serialize(profile);
    profile = SerializationUtils.deserialize(result);
    assertNull(profile.getAccessToken());
    assertEquals(profile.getIdTokenString(), ID_TOKEN);
    assertEquals(profile.getRefreshToken().getValue(), REFRESH_TOKEN);
}
Also used : RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) Test(org.junit.Test)

Aggregations

BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)5 RefreshToken (com.nimbusds.oauth2.sdk.token.RefreshToken)4 Test (org.junit.Test)4 ParseException (com.nimbusds.oauth2.sdk.ParseException)3 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)3 JOSEException (com.nimbusds.jose.JOSEException)2 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)2 JWT (com.nimbusds.jwt.JWT)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 IDTokenClaimsSet (com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet)2 SignedJWT (com.nimbusds.jwt.SignedJWT)1 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)1 TokenErrorResponse (com.nimbusds.oauth2.sdk.TokenErrorResponse)1 TokenRequest (com.nimbusds.oauth2.sdk.TokenRequest)1 TokenResponse (com.nimbusds.oauth2.sdk.TokenResponse)1 ClientAuthentication (com.nimbusds.oauth2.sdk.auth.ClientAuthentication)1 ClientSecretBasic (com.nimbusds.oauth2.sdk.auth.ClientSecretBasic)1 ClientSecretPost (com.nimbusds.oauth2.sdk.auth.ClientSecretPost)1 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)1 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)1