Search in sources :

Example 36 with TechnicalException

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

the class Pac4jAuthenticator method handle.

@Override
public void handle(Context ctx) throws Exception {
    PathBinding pathBinding = ctx.getPathBinding();
    String pastBinding = pathBinding.getPastBinding();
    if (pastBinding.equals(path)) {
        RatpackWebContext.from(ctx, true).flatMap(webContext -> {
            SessionData sessionData = webContext.getSession();
            return createClients(ctx, pathBinding).map(clients -> clients.findClient(webContext)).map(Types::<Client<Credentials, UserProfile>>cast).flatMap(client -> getProfile(webContext, client)).map(profile -> {
                if (profile != null) {
                    sessionData.set(Pac4jSessionKeys.USER_PROFILE, profile);
                }
                Optional<String> originalUrl = sessionData.get(Pac4jSessionKeys.REQUESTED_URL);
                sessionData.remove(Pac4jSessionKeys.REQUESTED_URL);
                return originalUrl;
            }).onError(t -> {
                if (t instanceof RequiresHttpAction) {
                    webContext.sendResponse((RequiresHttpAction) t);
                } else {
                    ctx.error(new TechnicalException("Failed to get user profile", t));
                }
            });
        }).then(originalUrlOption -> {
            ctx.redirect(originalUrlOption.orElse("/"));
        });
    } else {
        createClients(ctx, pathBinding).then(clients -> {
            Registry registry = Registry.singleLazy(Clients.class, () -> uncheck(() -> clients));
            ctx.next(registry);
        });
    }
}
Also used : Types(ratpack.util.Types) Context(ratpack.handling.Context) RatpackPac4j(ratpack.pac4j.RatpackPac4j) Exceptions.uncheck(ratpack.util.Exceptions.uncheck) Promise(ratpack.exec.Promise) PublicAddress(ratpack.server.PublicAddress) Blocking(ratpack.exec.Blocking) RequiresHttpAction(org.pac4j.core.exception.RequiresHttpAction) WebContext(org.pac4j.core.context.WebContext) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Clients(org.pac4j.core.client.Clients) Client(org.pac4j.core.client.Client) Handler(ratpack.handling.Handler) Registry(ratpack.registry.Registry) Optional(java.util.Optional) PathBinding(ratpack.path.PathBinding) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SessionData(ratpack.session.SessionData) Credentials(org.pac4j.core.credentials.Credentials) Types(ratpack.util.Types) RequiresHttpAction(org.pac4j.core.exception.RequiresHttpAction) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SessionData(ratpack.session.SessionData) Registry(ratpack.registry.Registry) PathBinding(ratpack.path.PathBinding) Credentials(org.pac4j.core.credentials.Credentials)

Example 37 with TechnicalException

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

the class SAML2ClientLogoutAction method doExecute.

@Override
protected Event doExecute(final RequestContext requestContext) {
    try {
        final HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext);
        final HttpServletResponse response = WebUtils.getHttpServletResponseFromExternalWebflowContext(requestContext);
        final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
        Client<?, ?> client;
        try {
            final String currentClientName = findCurrentClientName(context);
            client = (currentClientName == null) ? null : clients.findClient(currentClientName);
        } catch (final TechnicalException e) {
            LOGGER.debug("No SAML2 client found: " + e.getMessage(), e);
            client = null;
        }
        if (client instanceof SAML2Client) {
            final SAML2Client saml2Client = (SAML2Client) client;
            LOGGER.debug("Located SAML2 client [{}]", saml2Client);
            final RedirectAction action = saml2Client.getLogoutAction(context, null, null);
            LOGGER.debug("Preparing logout message to send is [{}]", action.getLocation());
            action.perform(context);
        } else {
            LOGGER.debug("The current client is not a SAML2 client or it cannot be found at all, no logout action will be executed.");
        }
    } catch (final Exception e) {
        LOGGER.warn(e.getMessage(), e);
    }
    return null;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) TechnicalException(org.pac4j.core.exception.TechnicalException) HttpServletResponse(javax.servlet.http.HttpServletResponse) SAML2Client(org.pac4j.saml.client.SAML2Client) J2EContext(org.pac4j.core.context.J2EContext) TechnicalException(org.pac4j.core.exception.TechnicalException) RedirectAction(org.pac4j.core.redirect.RedirectAction)

Example 38 with TechnicalException

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

the class OAuthCredentialsExtractor method extract.

@Override
public C extract(final WebContext context) {
    final boolean hasBeenCancelled = (Boolean) configuration.getHasBeenCancelledFactory().apply(context);
    // check if the authentication has been cancelled
    if (hasBeenCancelled) {
        logger.debug("authentication has been cancelled by user");
        return null;
    }
    // check errors
    try {
        boolean errorFound = false;
        final OAuthCredentialsException oauthCredentialsException = new OAuthCredentialsException("Failed to retrieve OAuth credentials, error parameters found");
        for (final String key : OAuthCredentialsException.ERROR_NAMES) {
            final String value = context.getRequestParameter(key);
            if (value != null) {
                errorFound = true;
                oauthCredentialsException.setErrorMessage(key, value);
            }
        }
        if (errorFound) {
            throw oauthCredentialsException;
        } else {
            return getOAuthCredentials(context);
        }
    } catch (final OAuthException e) {
        throw new TechnicalException(e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) OAuthException(com.github.scribejava.core.exceptions.OAuthException) OAuthCredentialsException(org.pac4j.oauth.exception.OAuthCredentialsException)

Example 39 with TechnicalException

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

the class SAML2IdentityProviderMetadataResolver method resolve.

@Override
public final MetadataResolver resolve() {
    // Usage of locks will adversly impact performance.
    if (idpMetadataProvider != null) {
        return idpMetadataProvider;
    }
    try {
        if (this.idpMetadataResource == null) {
            throw new XMLParserException("idp metadata cannot be resolved from " + this.idpMetadataResource);
        }
        try (final InputStream in = this.idpMetadataResource.getInputStream()) {
            final Document inCommonMDDoc = Configuration.getParserPool().parse(in);
            final Element metadataRoot = inCommonMDDoc.getDocumentElement();
            idpMetadataProvider = new DOMMetadataResolver(metadataRoot);
            idpMetadataProvider.setParserPool(Configuration.getParserPool());
            idpMetadataProvider.setFailFastInitialization(true);
            idpMetadataProvider.setRequireValidMetadata(true);
            idpMetadataProvider.setId(idpMetadataProvider.getClass().getCanonicalName());
            idpMetadataProvider.initialize();
        } catch (final FileNotFoundException e) {
            throw new TechnicalException("Error loading idp Metadata");
        }
        // If no idpEntityId declared, select first EntityDescriptor entityId as our IDP entityId
        if (this.idpEntityId == null) {
            final Iterator<EntityDescriptor> it = idpMetadataProvider.iterator();
            while (it.hasNext()) {
                final EntityDescriptor entityDescriptor = it.next();
                if (this.idpEntityId == null) {
                    this.idpEntityId = entityDescriptor.getEntityID();
                }
            }
        }
        if (this.idpEntityId == null) {
            throw new SAMLException("No idp entityId found");
        }
    } catch (final ComponentInitializationException e) {
        throw new SAMLException("Error initializing idpMetadataProvider", e);
    } catch (final XMLParserException e) {
        throw new TechnicalException("Error parsing idp Metadata", e);
    } catch (final IOException e) {
        throw new TechnicalException("Error getting idp Metadata resource", e);
    }
    return idpMetadataProvider;
}
Also used : DOMMetadataResolver(org.opensaml.saml.metadata.resolver.impl.DOMMetadataResolver) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) TechnicalException(org.pac4j.core.exception.TechnicalException) ComponentInitializationException(net.shibboleth.utilities.java.support.component.ComponentInitializationException) XMLParserException(net.shibboleth.utilities.java.support.xml.XMLParserException) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAMLException(org.pac4j.saml.exceptions.SAMLException)

Example 40 with TechnicalException

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

the class SunJaasKerberosTicketValidator method internalInit.

@Override
protected void internalInit() {
    // then internalInit() runs lazily during the first validateTicket() call
    try {
        CommonHelper.assertNotNull("servicePrincipal must be specified", this.servicePrincipal);
        CommonHelper.assertNotNull("keyTab must be specified", this.keyTabLocation);
        String keyTabLocationAsString = this.keyTabLocation.getURL().toExternalForm();
        // As Java 6 accepts it with and without the prefix, we don't need to check for Java 7
        if (keyTabLocationAsString.startsWith("file:")) {
            keyTabLocationAsString = keyTabLocationAsString.substring(5);
        }
        LoginConfig loginConfig = new LoginConfig(keyTabLocationAsString, this.servicePrincipal, this.debug);
        Set<Principal> princ = new HashSet<>(1);
        princ.add(new KerberosPrincipal(this.servicePrincipal));
        Subject sub = new Subject(false, princ, new HashSet<>(), new HashSet<>());
        LoginContext lc = new LoginContext("", sub, null, loginConfig);
        lc.login();
        this.serviceSubject = lc.getSubject();
    } catch (final LoginException | IOException e) {
        throw new TechnicalException(e);
    }
}
Also used : KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) TechnicalException(org.pac4j.core.exception.TechnicalException) IOException(java.io.IOException) Subject(javax.security.auth.Subject) LoginContext(javax.security.auth.login.LoginContext) LoginException(javax.security.auth.login.LoginException) KerberosPrincipal(javax.security.auth.kerberos.KerberosPrincipal) Principal(java.security.Principal) HashSet(java.util.HashSet)

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