Search in sources :

Example 61 with TechnicalException

use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.

the class OidcLogoutActionBuilder method getLogoutAction.

@Override
public Optional<RedirectionAction> getLogoutAction(final WebContext context, final SessionStore sessionStore, final UserProfile currentProfile, final String targetUrl) {
    final var logoutUrl = configuration.findLogoutUrl();
    if (CommonHelper.isNotBlank(logoutUrl) && currentProfile instanceof OidcProfile) {
        try {
            final var endSessionEndpoint = new URI(logoutUrl);
            final var idToken = ((OidcProfile) 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, sessionStore)) {
                sessionStore.set(context, Pac4jConstants.REQUESTED_URL, null);
                context.setResponseHeader(HttpConstants.LOCATION_HEADER, logoutRequest.toURI().toString());
                throw ForbiddenAction.INSTANCE;
            }
            return Optional.of(HttpActionHelper.buildRedirectUrlAction(context, logoutRequest.toURI().toString()));
        } catch (final URISyntaxException e) {
            throw new TechnicalException(e);
        }
    }
    return Optional.empty();
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) OidcProfile(org.pac4j.oidc.profile.OidcProfile) LogoutRequest(com.nimbusds.openid.connect.sdk.LogoutRequest) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 62 with TechnicalException

use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.

the class TokenValidator method validate.

public IDTokenClaimsSet validate(final JWT idToken, final Nonce expectedNonce) throws BadJOSEException, JOSEException {
    BadJOSEException badJOSEException = null;
    JOSEException joseException = null;
    for (final var idTokenValidator : idTokenValidators) {
        try {
            return idTokenValidator.validate(idToken, expectedNonce);
        } catch (final BadJOSEException e1) {
            logger.debug(e1.getMessage(), e1);
            badJOSEException = e1;
        } catch (final JOSEException e2) {
            logger.debug(e2.getMessage(), e2);
            joseException = e2;
        }
    }
    if (badJOSEException != null) {
        throw badJOSEException;
    } else if (joseException != null) {
        throw joseException;
    } else {
        throw new TechnicalException("Unable to validate the ID token");
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Example 63 with TechnicalException

use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.

the class OidcAuthenticator method refresh.

public void refresh(final OidcCredentials credentials) {
    final var refreshToken = credentials.getRefreshToken();
    if (refreshToken != null) {
        try {
            final var request = createTokenRequest(new RefreshTokenGrant(refreshToken));
            executeTokenRequest(request, credentials);
        } catch (final IOException | ParseException e) {
            throw new TechnicalException(e);
        }
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) IOException(java.io.IOException)

Example 64 with TechnicalException

use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.

the class OidcAuthenticator method validate.

@Override
public void validate(final Credentials cred, final WebContext context, final SessionStore sessionStore) {
    final var credentials = (OidcCredentials) cred;
    final var code = credentials.getCode();
    // if we have a code
    if (code != null) {
        try {
            final var computedCallbackUrl = client.computeFinalCallbackUrl(context);
            var verifier = (CodeVerifier) configuration.getValueRetriever().retrieve(client.getCodeVerifierSessionAttributeName(), client, context, sessionStore).orElse(null);
            // Token request
            final var request = createTokenRequest(new AuthorizationCodeGrant(code, new URI(computedCallbackUrl), verifier));
            executeTokenRequest(request, credentials);
        } catch (final URISyntaxException | IOException | ParseException e) {
            throw new TechnicalException(e);
        }
    }
}
Also used : CodeVerifier(com.nimbusds.oauth2.sdk.pkce.CodeVerifier) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) TechnicalException(org.pac4j.core.exception.TechnicalException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI)

Example 65 with TechnicalException

use of org.pac4j.core.exception.TechnicalException in project pac4j by pac4j.

the class OidcExtractor method extract.

@Override
public Optional<Credentials> extract(final WebContext context, final SessionStore sessionStore) {
    final var logoutEndpoint = context.getRequestParameter(Pac4jConstants.LOGOUT_ENDPOINT_PARAMETER).isPresent();
    if (logoutEndpoint) {
        final var logoutToken = context.getRequestParameter("logout_token");
        // back-channel logout
        if (logoutToken.isPresent()) {
            try {
                final var jwt = JWTParser.parse(logoutToken.get());
                // we should use the tokenValidator, but we can't as validation fails on missing claims: exp, iat...
                // final IDTokenClaimsSet claims = configuration.findTokenValidator().validate(jwt, null);
                // final String sid = (String) claims.getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID);
                final var sid = (String) jwt.getJWTClaimsSet().getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID);
                logger.debug("Handling back-channel logout for sessionId: {}", sid);
                configuration.findLogoutHandler().destroySessionBack(context, sessionStore, sid);
            } catch (final java.text.ParseException e) {
                logger.error("Cannot validate JWT logout token", e);
                throw BadRequestAction.INSTANCE;
            }
        } else {
            final var sid = context.getRequestParameter(Pac4jConstants.OIDC_CLAIM_SESSIONID).orElse(null);
            logger.debug("Handling front-channel logout for sessionId: {}", sid);
            // front-channel logout
            configuration.findLogoutHandler().destroySessionFront(context, sessionStore, sid);
        }
        context.setResponseHeader("Cache-Control", "no-cache, no-store");
        context.setResponseHeader("Pragma", "no-cache");
        throw new OkAction("");
    } else {
        final var computedCallbackUrl = client.computeFinalCallbackUrl(context);
        final var parameters = retrieveParameters(context);
        AuthenticationResponse response;
        try {
            response = AuthenticationResponseParser.parse(new URI(computedCallbackUrl), parameters);
        } catch (final URISyntaxException | ParseException e) {
            throw new TechnicalException(e);
        }
        if (response instanceof AuthenticationErrorResponse) {
            logger.error("Bad authentication response, error={}", ((AuthenticationErrorResponse) response).getErrorObject());
            return Optional.empty();
        }
        logger.debug("Authentication response successful");
        var successResponse = (AuthenticationSuccessResponse) response;
        if (configuration.isWithState()) {
            // Validate state for CSRF mitigation
            final var requestState = (State) configuration.getValueRetriever().retrieve(client.getStateSessionAttributeName(), client, context, sessionStore).orElseThrow(() -> new TechnicalException("State cannot be determined"));
            final var responseState = successResponse.getState();
            if (responseState == null) {
                throw new TechnicalException("Missing state parameter");
            }
            logger.debug("Request state: {}/response state: {}", requestState, responseState);
            if (!requestState.equals(responseState)) {
                throw new TechnicalException("State parameter is different from the one sent in authentication request.");
            }
        }
        final var credentials = new OidcCredentials();
        // get authorization code
        final var code = successResponse.getAuthorizationCode();
        if (code != null) {
            credentials.setCode(code);
        }
        // get ID token
        final var idToken = successResponse.getIDToken();
        if (idToken != null) {
            credentials.setIdToken(idToken);
        }
        // get access token
        final var accessToken = successResponse.getAccessToken();
        if (accessToken != null) {
            credentials.setAccessToken(accessToken);
        }
        return Optional.of(credentials);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) AuthenticationErrorResponse(com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse) URISyntaxException(java.net.URISyntaxException) AuthenticationResponse(com.nimbusds.openid.connect.sdk.AuthenticationResponse) URI(java.net.URI) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) State(com.nimbusds.oauth2.sdk.id.State) WebContext(org.pac4j.core.context.WebContext) ParseException(com.nimbusds.oauth2.sdk.ParseException) OkAction(org.pac4j.core.exception.http.OkAction)

Aggregations

TechnicalException (org.pac4j.core.exception.TechnicalException)81 IOException (java.io.IOException)26 URI (java.net.URI)7 URISyntaxException (java.net.URISyntaxException)7 HashMap (java.util.HashMap)7 OAuthException (com.github.scribejava.core.exceptions.OAuthException)6 JWT (com.nimbusds.jwt.JWT)6 ParseException (com.nimbusds.oauth2.sdk.ParseException)6 HttpURLConnection (java.net.HttpURLConnection)6 Test (org.junit.Test)6 OidcCredentials (org.pac4j.oidc.credentials.OidcCredentials)6 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)5 SignedJWT (com.nimbusds.jwt.SignedJWT)5 ArrayList (java.util.ArrayList)5 ComponentInitializationException (net.shibboleth.utilities.java.support.component.ComponentInitializationException)5 JOSEException (com.nimbusds.jose.JOSEException)4 URL (java.net.URL)4 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)3 HTTPResponse (com.nimbusds.oauth2.sdk.http.HTTPResponse)3 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)3