Search in sources :

Example 11 with JWT

use of com.nimbusds.jwt.JWT in project ddf by codice.

the class OidcTokenValidatorTest method testValidateIdTokens.

@Test
public void testValidateIdTokens() throws Exception {
    WebContext context = getWebContext();
    String stringJwt = getIdTokenBuilder().withClaim("nonce", "myNonce").sign(validAlgorithm);
    JWT jwt = SignedJWT.parse(stringJwt);
    OidcTokenValidator.validateIdTokens(jwt, context, configuration, oidcClient);
}
Also used : WebContext(org.pac4j.core.context.WebContext) PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) Test(org.junit.Test)

Example 12 with JWT

use of com.nimbusds.jwt.JWT in project ddf by codice.

the class OidcTokenValidatorTest method testValidateAccessTokenInvalidSignature.

@Test(expected = OidcValidationException.class)
public void testValidateAccessTokenInvalidSignature() throws Exception {
    String accessTokenString = getAccessTokenBuilder().sign(invalidAlgorithm);
    AccessToken accessToken = new BearerAccessToken(accessTokenString);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    messageDigest.update(accessTokenString.getBytes(Charset.forName("US-ASCII")));
    byte[] hash = messageDigest.digest();
    byte[] firstHalf = Arrays.copyOf(hash, hash.length / 2);
    String idToken = getIdTokenBuilder().withClaim("nonce", "myNonce").withClaim("at_hash", Base64URL.encode(firstHalf).toString()).sign(validAlgorithm);
    JWT jwt = SignedJWT.parse(idToken);
    OidcTokenValidator.validateAccessToken(accessToken, jwt, resourceRetriever, oidcProviderMetadata, configuration);
}
Also used : AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) MessageDigest(java.security.MessageDigest) Test(org.junit.Test)

Example 13 with JWT

use of com.nimbusds.jwt.JWT in project ddf by codice.

the class OidcTokenValidatorTest method testValidateIdTokensInvalidNonce.

@Test(expected = OidcValidationException.class)
public void testValidateIdTokensInvalidNonce() throws Exception {
    WebContext context = getWebContext();
    String stringJwt = getIdTokenBuilder().withClaim("nonce", "WRONG").sign(validAlgorithm);
    JWT jwt = SignedJWT.parse(stringJwt);
    OidcTokenValidator.validateIdTokens(jwt, context, configuration, oidcClient);
}
Also used : WebContext(org.pac4j.core.context.WebContext) PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) Test(org.junit.Test)

Example 14 with JWT

use of com.nimbusds.jwt.JWT 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)

Example 15 with JWT

use of com.nimbusds.jwt.JWT in project pac4j by pac4j.

the class OidcLogoutActionBuilder method getLogoutAction.

@Override
public RedirectAction getLogoutAction(final WebContext context, final U currentProfile, final String targetUrl) {
    final String logoutUrl = configuration.getLogoutUrl();
    if (CommonHelper.isNotBlank(logoutUrl)) {
        try {
            final URI endSessionEndpoint = new URI(logoutUrl);
            final JWT idToken = currentProfile.getIdToken();
            LogoutRequest logoutRequest;
            if (CommonHelper.isNotBlank(targetUrl)) {
                logoutRequest = new LogoutRequest(endSessionEndpoint, idToken, new URI(targetUrl), null);
            } else {
                logoutRequest = new LogoutRequest(endSessionEndpoint, idToken);
            }
            if (ajaxRequestResolver.isAjax(context)) {
                context.getSessionStore().set(context, Pac4jConstants.REQUESTED_URL, "");
                context.setResponseHeader(HttpConstants.LOCATION_HEADER, logoutRequest.toURI().toString());
                throw HttpAction.status(403, context);
            }
            return RedirectAction.redirect(logoutRequest.toURI().toString());
        } catch (final URISyntaxException e) {
            throw new TechnicalException(e);
        }
    }
    return null;
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) JWT(com.nimbusds.jwt.JWT) LogoutRequest(com.nimbusds.openid.connect.sdk.LogoutRequest) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Aggregations

JWT (com.nimbusds.jwt.JWT)28 SignedJWT (com.nimbusds.jwt.SignedJWT)17 PlainJWT (com.nimbusds.jwt.PlainJWT)16 Test (org.junit.Test)14 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)9 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)9 WebContext (org.pac4j.core.context.WebContext)7 TechnicalException (org.pac4j.core.exception.TechnicalException)6 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)5 JOSEException (com.nimbusds.jose.JOSEException)4 ParseException (com.nimbusds.oauth2.sdk.ParseException)4 IOException (java.io.IOException)4 ParseException (java.text.ParseException)4 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)3 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)3 URI (java.net.URI)3 Date (java.util.Date)3 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)2 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)2 Resource (com.nimbusds.jose.util.Resource)2