Search in sources :

Example 1 with OIDCTokens

use of com.nimbusds.openid.connect.sdk.token.OIDCTokens in project pac4j by pac4j.

the class OidcAuthenticator method validate.

@Override
public void validate(final OidcCredentials credentials, final WebContext context) {
    final AuthorizationCode code = credentials.getCode();
    // if we have a code
    if (code != null) {
        try {
            final String computedCallbackUrl = client.computeFinalCallbackUrl(context);
            // Token request
            final TokenRequest request = new TokenRequest(configuration.findProviderMetadata().getTokenEndpointURI(), this.clientAuthentication, new AuthorizationCodeGrant(code, new URI(computedCallbackUrl)));
            HTTPRequest tokenHttpRequest = request.toHTTPRequest();
            tokenHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
            tokenHttpRequest.setReadTimeout(configuration.getReadTimeout());
            final HTTPResponse httpResponse = tokenHttpRequest.send();
            logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
            final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse);
            if (response instanceof TokenErrorResponse) {
                throw new TechnicalException("Bad token response, error=" + ((TokenErrorResponse) response).getErrorObject());
            }
            logger.debug("Token response successful");
            final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response;
            // save tokens in credentials
            final OIDCTokens oidcTokens = tokenSuccessResponse.getOIDCTokens();
            credentials.setAccessToken(oidcTokens.getAccessToken());
            credentials.setRefreshToken(oidcTokens.getRefreshToken());
            credentials.setIdToken(oidcTokens.getIDToken());
        } catch (final URISyntaxException | IOException | ParseException e) {
            throw new TechnicalException(e);
        }
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens)

Example 2 with OIDCTokens

use of com.nimbusds.openid.connect.sdk.token.OIDCTokens in project ddf by codice.

the class OidcCredentialsResolver method trySendingGrantAndPopulatingCredentials.

private void trySendingGrantAndPopulatingCredentials(AuthorizationGrant grant, OidcCredentials credentials, WebContext webContext) throws IOException, ParseException {
    final OIDCTokens oidcTokens = getOidcTokens(grant);
    try {
        JWT idToken = oidcTokens.getIDToken();
        if (idToken != null) {
            OidcTokenValidator.validateIdTokens(idToken, webContext, configuration, client);
        }
        AccessToken accessToken = oidcTokens.getAccessToken();
        if (accessToken != null) {
            OidcTokenValidator.validateAccessToken(accessToken, idToken, resourceRetriever, metadata, configuration);
        }
        credentials.setAccessToken(accessToken);
        credentials.setIdToken(idToken);
        credentials.setRefreshToken(oidcTokens.getRefreshToken());
    } catch (OidcValidationException e) {
        throw new TechnicalException(e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) OidcValidationException(org.codice.ddf.security.oidc.validator.OidcValidationException)

Example 3 with OIDCTokens

use of com.nimbusds.openid.connect.sdk.token.OIDCTokens in project nifi by apache.

the class StandardOidcIdentityProvider method exchangeAuthorizationCode.

@Override
public String exchangeAuthorizationCode(final AuthorizationGrant authorizationGrant) throws IOException {
    if (!isOidcEnabled()) {
        throw new IllegalStateException(OPEN_ID_CONNECT_SUPPORT_IS_NOT_CONFIGURED);
    }
    final ClientAuthentication clientAuthentication;
    if (oidcProviderMetadata.getTokenEndpointAuthMethods().contains(ClientAuthenticationMethod.CLIENT_SECRET_POST)) {
        clientAuthentication = new ClientSecretPost(clientId, clientSecret);
    } else {
        clientAuthentication = new ClientSecretBasic(clientId, clientSecret);
    }
    try {
        // build the token request
        final TokenRequest request = new TokenRequest(oidcProviderMetadata.getTokenEndpointURI(), clientAuthentication, authorizationGrant, getScope());
        final HTTPRequest tokenHttpRequest = request.toHTTPRequest();
        tokenHttpRequest.setConnectTimeout(oidcConnectTimeout);
        tokenHttpRequest.setReadTimeout(oidcReadTimeout);
        // get the token response
        final TokenResponse response = OIDCTokenResponseParser.parse(tokenHttpRequest.send());
        if (response.indicatesSuccess()) {
            final OIDCTokenResponse oidcTokenResponse = (OIDCTokenResponse) response;
            final OIDCTokens oidcTokens = oidcTokenResponse.getOIDCTokens();
            final JWT oidcJwt = oidcTokens.getIDToken();
            // validate the token - no nonce required for authorization code flow
            final IDTokenClaimsSet claimsSet = tokenValidator.validate(oidcJwt, null);
            // attempt to extract the email from the id token if possible
            String email = claimsSet.getStringClaim(EMAIL_CLAIM_NAME);
            if (StringUtils.isBlank(email)) {
                // extract the bearer access token
                final BearerAccessToken bearerAccessToken = oidcTokens.getBearerAccessToken();
                if (bearerAccessToken == null) {
                    throw new IllegalStateException("No access token found in the ID tokens");
                }
                // invoke the UserInfo endpoint
                email = lookupEmail(bearerAccessToken);
            }
            // extract expiration details from the claims set
            final Calendar now = Calendar.getInstance();
            final Date expiration = claimsSet.getExpirationTime();
            final long expiresIn = expiration.getTime() - now.getTimeInMillis();
            // convert into a nifi jwt for retrieval later
            final LoginAuthenticationToken loginToken = new LoginAuthenticationToken(email, email, expiresIn, claimsSet.getIssuer().getValue());
            return jwtService.generateSignedToken(loginToken);
        } else {
            final TokenErrorResponse errorResponse = (TokenErrorResponse) response;
            throw new RuntimeException("An error occurred while invoking the Token endpoint: " + errorResponse.getErrorObject().getDescription());
        }
    } catch (final ParseException | JOSEException | BadJOSEException e) {
        throw new RuntimeException("Unable to parse the response from the Token request: " + e.getMessage());
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) JWT(com.nimbusds.jwt.JWT) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) Calendar(java.util.Calendar) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) ClientSecretBasic(com.nimbusds.oauth2.sdk.auth.ClientSecretBasic) Date(java.util.Date) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) ClientSecretPost(com.nimbusds.oauth2.sdk.auth.ClientSecretPost) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) TokenResponse(com.nimbusds.oauth2.sdk.TokenResponse) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) LoginAuthenticationToken(org.apache.nifi.web.security.token.LoginAuthenticationToken) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) ParseException(com.nimbusds.oauth2.sdk.ParseException) ClientAuthentication(com.nimbusds.oauth2.sdk.auth.ClientAuthentication) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Aggregations

OIDCTokens (com.nimbusds.openid.connect.sdk.token.OIDCTokens)3 JWT (com.nimbusds.jwt.JWT)2 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)2 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)2 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)2 TechnicalException (org.pac4j.core.exception.TechnicalException)2 JOSEException (com.nimbusds.jose.JOSEException)1 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)1 PlainJWT (com.nimbusds.jwt.PlainJWT)1 ParseException (com.nimbusds.oauth2.sdk.ParseException)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 IDTokenClaimsSet (com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet)1 IOException (java.io.IOException)1