Search in sources :

Example 11 with TechnicalException

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

the class SAML2ClientConfiguration method internalInit.

@Override
protected void internalInit() {
    CommonHelper.assertNotNull("keystoreResource", this.keystoreResource);
    CommonHelper.assertNotBlank("keystorePassword", this.keystorePassword);
    CommonHelper.assertNotBlank("privateKeyPassword", this.privateKeyPassword);
    CommonHelper.assertNotNull("identityProviderMetadataResource", this.identityProviderMetadataResource);
    if (!this.keystoreResource.exists()) {
        if (this.keystoreResource instanceof WritableResource) {
            LOGGER.warn("Provided keystoreResource does not exist. Creating one for: {}", this.keystoreResource);
            createKeystore();
        } else {
            throw new TechnicalException("Provided keystoreResource does not exist and cannot be created");
        }
    }
    final BasicSignatureSigningConfiguration config = DefaultSecurityConfigurationBootstrap.buildDefaultSignatureSigningConfiguration();
    this.blackListedSignatureSigningAlgorithms = new ArrayList<>(config.getBlacklistedAlgorithms());
    this.signatureAlgorithms = new ArrayList<>(config.getSignatureAlgorithms());
    this.signatureReferenceDigestMethods = new ArrayList<>(config.getSignatureReferenceDigestMethods());
    this.signatureReferenceDigestMethods.remove("http://www.w3.org/2001/04/xmlenc#sha512");
    this.signatureCanonicalizationAlgorithm = config.getSignatureCanonicalizationAlgorithm();
}
Also used : WritableResource(org.springframework.core.io.WritableResource) TechnicalException(org.pac4j.core.exception.TechnicalException) BasicSignatureSigningConfiguration(org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration)

Example 12 with TechnicalException

use of org.pac4j.core.exception.TechnicalException 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 13 with TechnicalException

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

the class OidcExtractor method extract.

@Override
public OidcCredentials extract(final WebContext context) {
    final String computedCallbackUrl = client.computeFinalCallbackUrl(context);
    final Map<String, String> 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 null;
    }
    logger.debug("Authentication response successful");
    AuthenticationSuccessResponse successResponse = (AuthenticationSuccessResponse) response;
    final State state = successResponse.getState();
    if (state == null) {
        throw new TechnicalException("Missing state parameter");
    }
    if (!state.equals(context.getSessionStore().get(context, OidcConfiguration.STATE_SESSION_ATTRIBUTE))) {
        throw new TechnicalException("State parameter is different from the one sent in authentication request. " + "Session expired or possible threat of cross-site request forgery");
    }
    final OidcCredentials credentials = new OidcCredentials();
    // get authorization code
    final AuthorizationCode code = successResponse.getAuthorizationCode();
    if (code != null) {
        credentials.setCode(code);
    }
    // get ID token
    final JWT idToken = successResponse.getIDToken();
    if (idToken != null) {
        credentials.setIdToken(idToken);
    }
    // get access token
    final AccessToken accessToken = successResponse.getAccessToken();
    if (accessToken != null) {
        credentials.setAccessToken(accessToken);
    }
    return credentials;
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) TechnicalException(org.pac4j.core.exception.TechnicalException) JWT(com.nimbusds.jwt.JWT) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) OidcCredentials(org.pac4j.oidc.credentials.OidcCredentials) State(com.nimbusds.oauth2.sdk.id.State) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) ParseException(com.nimbusds.oauth2.sdk.ParseException)

Example 14 with TechnicalException

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

the class OidcProfileCreator method create.

@Override
@SuppressWarnings("unchecked")
public U create(final OidcCredentials credentials, final WebContext context) {
    init();
    final AccessToken accessToken = credentials.getAccessToken();
    // Create profile
    final U profile = getProfileDefinition().newProfile();
    profile.setAccessToken(accessToken);
    final JWT idToken = credentials.getIdToken();
    profile.setIdTokenString(idToken.getParsedString());
    // Check if there is a refresh token
    final RefreshToken refreshToken = credentials.getRefreshToken();
    if (refreshToken != null && !refreshToken.getValue().isEmpty()) {
        profile.setRefreshToken(refreshToken);
        logger.debug("Refresh Token successful retrieved");
    }
    try {
        // check idToken
        final Nonce nonce;
        if (configuration.isUseNonce()) {
            nonce = new Nonce((String) context.getSessionStore().get(context, OidcConfiguration.NONCE_SESSION_ATTRIBUTE));
        } else {
            nonce = null;
        }
        // Check ID Token
        final IDTokenClaimsSet claimsSet = this.idTokenValidator.validate(idToken, nonce);
        assertNotNull("claimsSet", claimsSet);
        profile.setId(ProfileHelper.sanitizeIdentifier(profile, claimsSet.getSubject()));
        // User Info request
        if (configuration.findProviderMetadata().getUserInfoEndpointURI() != null && accessToken != null) {
            final UserInfoRequest userInfoRequest = new UserInfoRequest(configuration.findProviderMetadata().getUserInfoEndpointURI(), (BearerAccessToken) accessToken);
            final HTTPRequest userInfoHttpRequest = userInfoRequest.toHTTPRequest();
            userInfoHttpRequest.setConnectTimeout(configuration.getConnectTimeout());
            userInfoHttpRequest.setReadTimeout(configuration.getReadTimeout());
            final HTTPResponse httpResponse = userInfoHttpRequest.send();
            logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), httpResponse.getContent());
            final UserInfoResponse userInfoResponse = UserInfoResponse.parse(httpResponse);
            if (userInfoResponse instanceof UserInfoErrorResponse) {
                logger.error("Bad User Info response, error={}", ((UserInfoErrorResponse) userInfoResponse).getErrorObject());
            } else {
                final UserInfoSuccessResponse 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 Map.Entry<String, Object> entry : idToken.getJWTClaimsSet().getClaims().entrySet()) {
            final String key = entry.getKey();
            final Object 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);
            }
        }
        return profile;
    } catch (final IOException | ParseException | JOSEException | BadJOSEException | java.text.ParseException e) {
        throw new TechnicalException(e);
    }
}
Also used : HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) JWT(com.nimbusds.jwt.JWT) HTTPResponse(com.nimbusds.oauth2.sdk.http.HTTPResponse) IDTokenClaimsSet(com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet) IOException(java.io.IOException) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(com.nimbusds.oauth2.sdk.ParseException) Map(java.util.Map) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException)

Example 15 with TechnicalException

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

the class SAML2ServiceProviderMetadataResolver method resolve.

@Override
public final MetadataResolver resolve() {
    final boolean credentialProviderRequired = this.authnRequestSigned || this.wantsAssertionsSigned;
    if (credentialProviderRequired && this.credentialProvider == null) {
        throw new TechnicalException("Credentials Provider can not be null when authnRequestSigned or" + " wantsAssertionsSigned is set to true");
    }
    try {
        final SAML2MetadataGenerator metadataGenerator = new SAML2MetadataGenerator(binding);
        metadataGenerator.setWantAssertionSigned(this.wantsAssertionsSigned);
        metadataGenerator.setAuthnRequestSigned(this.authnRequestSigned);
        metadataGenerator.setNameIdPolicyFormat(this.nameIdPolicyFormat);
        if (credentialProviderRequired) {
            metadataGenerator.setCredentialProvider(this.credentialProvider);
        }
        metadataGenerator.setEntityId(this.spEntityId);
        metadataGenerator.setRequestInitiatorLocation(callbackUrl);
        // Assertion consumer service url is the callback url
        metadataGenerator.setAssertionConsumerServiceUrl(callbackUrl);
        // for now same for logout url
        metadataGenerator.setSingleLogoutServiceUrl(callbackUrl);
        final MetadataResolver spMetadataProvider = metadataGenerator.buildMetadataResolver();
        // Initialize metadata provider for our SP and get the XML as a String
        this.spMetadata = metadataGenerator.getMetadata();
        if (this.spMetadataResource != null) {
            if (spMetadataResource.exists() && !this.forceSpMetadataGeneration) {
                logger.info("Metadata file already exists at {}.", this.spMetadataResource.getFilename());
            } else {
                logger.info("Writing sp metadata to {}", this.spMetadataResource.getFilename());
                final File parent = spMetadataResource.getFile().getParentFile();
                if (parent != null) {
                    logger.info("Attempting to create directory structure for: {}", parent.getCanonicalPath());
                    if (!parent.exists() && !parent.mkdirs()) {
                        logger.warn("Could not construct the directory structure for SP metadata: {}", parent.getCanonicalPath());
                    }
                }
                final Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
                final StreamResult result = new StreamResult(new StringWriter());
                final StreamSource source = new StreamSource(new StringReader(this.spMetadata));
                transformer.transform(source, result);
                try (final OutputStream spMetadataOutputStream = this.spMetadataResource.getOutputStream()) {
                    spMetadataOutputStream.write(result.getWriter().toString().getBytes(StandardCharsets.UTF_8));
                }
            }
        }
        return spMetadataProvider;
    } catch (final ComponentInitializationException e) {
        throw new TechnicalException("Error initializing spMetadataProvider", e);
    } catch (final MarshallingException e) {
        logger.warn("Unable to marshal SP metadata", e);
    } catch (final IOException e) {
        logger.warn("Unable to print SP metadata", e);
    } catch (final Exception e) {
        logger.warn("Unable to transform metadata", e);
    }
    return null;
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) ComponentInitializationException(net.shibboleth.utilities.java.support.component.ComponentInitializationException) StreamSource(javax.xml.transform.stream.StreamSource) OutputStream(java.io.OutputStream) IOException(java.io.IOException) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) ComponentInitializationException(net.shibboleth.utilities.java.support.component.ComponentInitializationException) TechnicalException(org.pac4j.core.exception.TechnicalException) MarshallingException(org.opensaml.core.xml.io.MarshallingException) ResolverException(net.shibboleth.utilities.java.support.resolver.ResolverException) IOException(java.io.IOException) SAMLException(org.pac4j.saml.exceptions.SAMLException) StringWriter(java.io.StringWriter) MarshallingException(org.opensaml.core.xml.io.MarshallingException) StringReader(java.io.StringReader) File(java.io.File)

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