Search in sources :

Example 31 with TechnicalException

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

the class CasRestAuthenticator method requestTicketGrantingTicket.

private String requestTicketGrantingTicket(final String username, final String password, final WebContext context) {
    HttpURLConnection connection = null;
    try {
        connection = HttpUtils.openPostConnection(new URL(this.configuration.computeFinalRestUrl(context)));
        final var payload = HttpUtils.encodeQueryParam(Pac4jConstants.USERNAME, username) + "&" + HttpUtils.encodeQueryParam(Pac4jConstants.PASSWORD, password);
        final var out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8));
        out.write(payload);
        out.close();
        final var locationHeader = connection.getHeaderField("location");
        final var responseCode = connection.getResponseCode();
        if (locationHeader != null && responseCode == HttpConstants.CREATED) {
            return locationHeader.substring(locationHeader.lastIndexOf("/") + 1);
        }
        logger.debug("Ticket granting ticket request failed: " + locationHeader + " " + responseCode + HttpUtils.buildHttpErrorMessage(connection));
        return null;
    } catch (final IOException e) {
        throw new TechnicalException(e);
    } finally {
        HttpUtils.closeConnection(connection);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) TechnicalException(org.pac4j.core.exception.TechnicalException) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) URL(java.net.URL) BufferedWriter(java.io.BufferedWriter)

Example 32 with TechnicalException

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

the class FacebookProfileDefinition method computeAppSecretProof.

/**
 * The code in this method is based on this blog post:
 * https://www.sammyk.me/the-single-most-important-way-to-make-your-facebook-app-more-secure
 * and this answer: https://stackoverflow.com/questions/7124735/hmac-sha256-algorithm-for-signature-calculation
 *
 * @param url the URL to which we're adding the proof
 * @param token the application token we pass back and forth
 * @param configuration the current configuration
 * @return URL with the appsecret_proof parameter added
 */
public String computeAppSecretProof(final String url, final OAuth2AccessToken token, final FacebookConfiguration configuration) {
    try {
        var sha256_HMAC = Mac.getInstance("HmacSHA256");
        var secret_key = new SecretKeySpec(configuration.getSecret().getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        var proof = org.apache.commons.codec.binary.Hex.encodeHexString(sha256_HMAC.doFinal(token.getAccessToken().getBytes(StandardCharsets.UTF_8)));
        final var computedUrl = CommonHelper.addParameter(url, APPSECRET_PARAMETER, proof);
        return computedUrl;
    } catch (final InvalidKeyException | NoSuchAlgorithmException e) {
        throw new TechnicalException("Unable to compute appsecret_proof", e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 33 with TechnicalException

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

the class AzureAdClient method getAccessTokenFromRefreshToken.

public String getAccessTokenFromRefreshToken(final AzureAdProfile azureAdProfile) {
    final var azureConfig = (AzureAdOidcConfiguration) getConfiguration();
    CommonHelper.assertTrue(CommonHelper.isNotBlank(azureConfig.getTenant()), "Tenant must be defined. Update your config.");
    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);
        connection = HttpUtils.openPostConnection(new URL("https://login.microsoftonline.com/" + azureConfig.getTenant() + "/oauth2/token"), 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 : AzureAdOidcConfiguration(org.pac4j.oidc.config.AzureAdOidcConfiguration) TechnicalException(org.pac4j.core.exception.TechnicalException) HashMap(java.util.HashMap) IOException(java.io.IOException) URL(java.net.URL) BufferedWriter(java.io.BufferedWriter) HttpURLConnection(java.net.HttpURLConnection) OutputStreamWriter(java.io.OutputStreamWriter)

Example 34 with TechnicalException

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

the class OidcProfileCreator method create.

@Override
@SuppressWarnings("unchecked")
public Optional<UserProfile> create(final Credentials cred, final WebContext context, final SessionStore sessionStore) {
    init();
    final var credentials = (OidcCredentials) cred;
    final var accessToken = credentials.getAccessToken();
    // Create profile
    final var profile = (OidcProfile) getProfileDefinition().newProfile();
    profile.setAccessToken(accessToken);
    final var idToken = credentials.getIdToken();
    profile.setIdTokenString(idToken.getParsedString());
    // Check if there is a refresh token
    final var refreshToken = credentials.getRefreshToken();
    if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
        profile.setRefreshToken(refreshToken);
        logger.debug("Refresh Token successful retrieved");
    }
    try {
        final Nonce nonce;
        if (configuration.isUseNonce()) {
            nonce = new Nonce((String) sessionStore.get(context, client.getNonceSessionAttributeName()).orElse(null));
        } else {
            nonce = null;
        }
        // Check ID Token
        final var claimsSet = configuration.findTokenValidator().validate(idToken, nonce);
        assertNotNull("claimsSet", claimsSet);
        profile.setId(ProfileHelper.sanitizeIdentifier(claimsSet.getSubject()));
        // User Info request
        if (configuration.findProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
            final var userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), accessToken);
            final var userInfoHttpRequest = userInfoRequest.toHTTPRequest();
            configuration.configureHttpRequest(userInfoHttpRequest);
            final var httpResponse = userInfoHttpRequest.send();
            logger.debug("User info response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
            final var userInfoResponse = UserInfoResponse.parse(httpResponse);
            if (userInfoResponse instanceof UserInfoErrorResponse) {
                logger.error("Bad User Info response, error={}", ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
            } else {
                final var 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 var entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
            final var key = entry.getKey();
            final var 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);
            }
        }
        // session expiration with token behavior
        profile.setTokenExpirationAdvance(configuration.getTokenExpirationAdvance());
        // keep the session ID if provided
        final var sid = (String) claimsSet.getClaim(Pac4jConstants.OIDC_CLAIM_SESSIONID);
        if (isNotBlank(sid)) {
            configuration.findLogoutHandler().recordSession(context, sessionStore, sid);
        }
        return Optional.of(profile);
    } catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
        throw new TechnicalException(e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) IOException(java.io.IOException) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) OidcProfile(org.pac4j.oidc.profile.OidcProfile) ParseException(com.nimbusds.oauth2.sdk.ParseException) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Example 35 with TechnicalException

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

the class SAML2IdentityProviderMetadataResolverTest method resolveMetadataOverUrlWithHostnameVerifierFromConfig.

@Test
public void resolveMetadataOverUrlWithHostnameVerifierFromConfig() throws Exception {
    var configuration = new SAML2Configuration();
    configuration.setIdentityProviderMetadataResource(new UrlResource("https://self-signed.badssl.com"));
    configuration.setHostnameVerifier((s, sslSession) -> true);
    configuration.setSslSocketFactory(disabledSslContext().getSocketFactory());
    metadataResolver = new SAML2IdentityProviderMetadataResolver(configuration);
    try {
        metadataResolver.init();
    } catch (final TechnicalException e) {
        assertEquals(XMLParserException.class, e.getCause().getClass());
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) SAML2Configuration(org.pac4j.saml.config.SAML2Configuration) UrlResource(org.springframework.core.io.UrlResource) XMLParserException(net.shibboleth.utilities.java.support.xml.XMLParserException) Test(org.junit.Test)

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