Search in sources :

Example 56 with TechnicalException

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

the class JEEHttpActionAdapter method adapt.

@Override
public Object adapt(final HttpAction action, final WebContext context) {
    if (action != null) {
        var code = action.getCode();
        final var response = ((JEEContext) context).getNativeResponse();
        if (code < 400) {
            response.setStatus(code);
        } else {
            try {
                response.sendError(code);
            } catch (final IOException e) {
                throw new TechnicalException(e);
            }
        }
        if (action instanceof WithLocationAction) {
            final var withLocationAction = (WithLocationAction) action;
            context.setResponseHeader(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
        } else if (action instanceof WithContentAction) {
            final var withContentAction = (WithContentAction) action;
            final var content = withContentAction.getContent();
            if (content != null) {
                try {
                    response.getWriter().write(content);
                } catch (final IOException e) {
                    throw new TechnicalException(e);
                }
            }
        }
        return null;
    }
    throw new TechnicalException("No action provided");
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) JEEContext(org.pac4j.core.context.JEEContext) IOException(java.io.IOException)

Example 57 with TechnicalException

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

the class ECSignatureConfiguration method sign.

@Override
public SignedJWT sign(JWTClaimsSet claims) {
    init();
    CommonHelper.assertNotNull("privateKey", privateKey);
    try {
        final JWSSigner signer = new ECDSASigner(this.privateKey);
        final var signedJWT = new SignedJWT(new JWSHeader(algorithm), claims);
        signedJWT.sign(signer);
        return signedJWT;
    } catch (final JOSEException e) {
        throw new TechnicalException(e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT)

Example 58 with TechnicalException

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

the class AzureAd2Client method getAccessTokenFromRefreshToken.

/**
 * <p>Refresh the access token</p>
 * <p>https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token</p>
 */
@Override
public String getAccessTokenFromRefreshToken(final AzureAdProfile azureAdProfile) {
    final var azureConfig = (AzureAd2OidcConfiguration) getConfiguration();
    HttpURLConnection connection = null;
    try {
        final Map<String, String> headers = new HashMap<>();
        headers.put(HttpConstants.CONTENT_TYPE_HEADER, HttpConstants.APPLICATION_FORM_ENCODED_HEADER_VALUE);
        headers.put(HttpConstants.ACCEPT_HEADER, HttpConstants.APPLICATION_JSON);
        // get the token endpoint from discovery URI
        final var tokenEndpointURL = azureConfig.findProviderMetadata().getTokenEndpointURI().toURL();
        connection = HttpUtils.openPostConnection(tokenEndpointURL, headers);
        final var out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
        out.write(azureConfig.makeOauth2TokenRequest(azureAdProfile.getRefreshToken().getValue()));
        out.close();
        final var responseCode = connection.getResponseCode();
        if (responseCode != 200) {
            throw new TechnicalException("request for access token failed: " + HttpUtils.buildHttpErrorMessage(connection));
        }
        var body = HttpUtils.readBody(connection);
        final Map<String, Object> res = objectMapper.readValue(body, typeRef);
        return (String) res.get("access_token");
    } catch (final IOException e) {
        throw new TechnicalException(e);
    } finally {
        HttpUtils.closeConnection(connection);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TechnicalException(org.pac4j.core.exception.TechnicalException) HashMap(java.util.HashMap) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) AzureAd2OidcConfiguration(org.pac4j.oidc.config.AzureAd2OidcConfiguration) BufferedWriter(java.io.BufferedWriter)

Example 59 with TechnicalException

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

the class AppleOidcConfiguration method getSecret.

/**
 * Generate client secret (JWT) and cache it until expiration timeout
 */
@Override
public String getSecret() {
    if (store != null) {
        var cache = store.get(getClientId());
        if (cache.isPresent()) {
            return cache.get();
        }
    }
    // https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens#3262048
    var claimsSet = new JWTClaimsSet.Builder().issuer(getTeamID()).audience("https://appleid.apple.com").subject(getClientId()).issueTime(Date.from(Instant.now())).expirationTime(Date.from(Instant.now().plusSeconds(timeout.toSeconds()))).build();
    var signedJWT = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.ES256).keyID(privateKeyID).build(), claimsSet);
    JWSSigner signer;
    try {
        signer = new ECDSASigner(privateKey);
        signedJWT.sign(signer);
    } catch (JOSEException e) {
        throw new TechnicalException(e);
    }
    var secret = signedJWT.serialize();
    if (store != null) {
        store.set(getClientId(), secret);
    }
    return secret;
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JOSEException(com.nimbusds.jose.JOSEException) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 60 with TechnicalException

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

the class UserInfoOidcAuthenticator method fetchOidcProfile.

private JWTClaimsSet fetchOidcProfile(BearerAccessToken accessToken) {
    final var userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), accessToken);
    final var userInfoHttpRequest = userInfoRequest.toHTTPRequest();
    configuration.configureHttpRequest(userInfoHttpRequest);
    try {
        final var httpResponse = userInfoHttpRequest.send();
        logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
        final var userInfoResponse = UserInfoResponse.parse(httpResponse);
        if (userInfoResponse instanceof UserInfoErrorResponse) {
            throw new TechnicalException("Bad User Info response, error=" + ((UserInfoErrorResponse) userInfoResponse).getErrorObject().toJSONObject());
        } else {
            final var userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse;
            final JWTClaimsSet userInfoClaimsSet;
            if (userInfoSuccessResponse.getUserInfo() != null) {
                userInfoClaimsSet = userInfoSuccessResponse.getUserInfo().toJWTClaimsSet();
            } else {
                userInfoClaimsSet = userInfoSuccessResponse.getUserInfoJWT().getJWTClaimsSet();
            }
            return userInfoClaimsSet;
        }
    } catch (IOException | ParseException | java.text.ParseException e) {
        throw new TechnicalException(e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) 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) IOException(java.io.IOException) ParseException(com.nimbusds.oauth2.sdk.ParseException)

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