Search in sources :

Example 6 with Credentials

use of org.pac4j.core.credentials.Credentials in project cas by apereo.

the class OidcPrivateKeyJwtAuthenticator method validate.

@Override
public void validate(final Credentials creds, final WebContext webContext, final SessionStore sessionStore) {
    val credentials = (UsernamePasswordCredentials) creds;
    val registeredService = verifyCredentials(credentials, webContext);
    if (registeredService == null) {
        LOGGER.warn("Unable to verify credentials");
        return;
    }
    val clientId = registeredService.getClientId();
    val audience = casProperties.getServer().getPrefix().concat('/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.ACCESS_TOKEN_URL);
    val keys = OidcJsonWebKeyStoreUtils.getJsonWebKeySet(registeredService, applicationContext, Optional.of(OidcJsonWebKeyUsage.SIGNING));
    keys.ifPresent(Unchecked.consumer(jwks -> jwks.getJsonWebKeys().forEach(jsonWebKey -> {
        val consumer = new JwtConsumerBuilder().setVerificationKey(jsonWebKey.getKey()).setRequireSubject().setExpectedSubject(clientId).setRequireJwtId().setRequireExpirationTime().setExpectedIssuer(true, clientId).setExpectedAudience(true, audience).build();
        determineUserProfile(credentials, consumer);
    })));
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) Unchecked(org.jooq.lambda.Unchecked) CommonProfile(org.pac4j.core.profile.CommonProfile) SneakyThrows(lombok.SneakyThrows) OidcConstants(org.apereo.cas.oidc.OidcConstants) lombok.val(lombok.val) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) SessionStore(org.pac4j.core.context.session.SessionStore) ApplicationContext(org.springframework.context.ApplicationContext) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) JwtConsumer(org.jose4j.jwt.consumer.JwtConsumer) WebContext(org.pac4j.core.context.WebContext) Slf4j(lombok.extern.slf4j.Slf4j) AuditableExecution(org.apereo.cas.audit.AuditableExecution) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) OidcJsonWebKeyStoreUtils(org.apereo.cas.oidc.jwks.OidcJsonWebKeyStoreUtils) Optional(java.util.Optional) Credentials(org.pac4j.core.credentials.Credentials) ServiceFactory(org.apereo.cas.authentication.principal.ServiceFactory) Algorithm(com.nimbusds.jose.Algorithm) OidcJsonWebKeyUsage(org.apereo.cas.oidc.jwks.OidcJsonWebKeyUsage) ServicesManager(org.apereo.cas.services.ServicesManager) JwtConsumerBuilder(org.jose4j.jwt.consumer.JwtConsumerBuilder) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials)

Example 7 with Credentials

use of org.pac4j.core.credentials.Credentials in project cas by apereo.

the class DelegatedClientAuthenticationAction method doExecute.

@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();
    // web context
    final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);
    // get client
    final String clientName = request.getParameter(this.clients.getClientNameParameter());
    LOGGER.debug("clientName: [{}]", clientName);
    if (hasDelegationRequestFailed(request, response.getStatus()).isPresent()) {
        return stopWebflow();
    }
    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName);
        LOGGER.debug("Client: [{}]", client);
        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            LOGGER.debug("Retrieved credentials: [{}]", credentials);
        } catch (final Exception e) {
            LOGGER.debug("The request requires http action", e);
            return stopWebflow();
        }
        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(CasProtocolConstants.PARAMETER_SERVICE);
        context.getFlowScope().put(CasProtocolConstants.PARAMETER_SERVICE, service);
        LOGGER.debug("Retrieve service: [{}]", service);
        if (service != null) {
            request.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
        }
        restoreRequestAttribute(request, session, this.themeParamName);
        restoreRequestAttribute(request, session, this.localParamName);
        restoreRequestAttribute(request, session, CasProtocolConstants.PARAMETER_METHOD);
        // credentials not null -> try to authenticate
        if (credentials != null) {
            final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, new ClientCredential(credentials));
            final TicketGrantingTicket tgt = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
            WebUtils.putTicketGrantingTicketInScopes(context, tgt);
            return success();
        }
    }
    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    if (response.getStatus() == HttpStatus.UNAUTHORIZED.value()) {
        return stopWebflow();
    }
    if (this.autoRedirect) {
        final Set<ProviderLoginPageConfiguration> urls = context.getFlowScope().get(PAC4J_URLS, Set.class);
        if (urls != null && urls.size() == 1) {
            final ProviderLoginPageConfiguration cfg = urls.stream().findFirst().get();
            LOGGER.debug("Auto-redirecting to client url [{}]", cfg.getRedirectUrl());
            response.sendRedirect(cfg.getRedirectUrl());
            final ExternalContext externalContext = context.getExternalContext();
            externalContext.recordResponseComplete();
            return stopWebflow();
        }
    }
    return error();
}
Also used : WebContext(org.pac4j.core.context.WebContext) HttpSession(javax.servlet.http.HttpSession) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) HttpServletResponse(javax.servlet.http.HttpServletResponse) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) Service(org.apereo.cas.authentication.principal.Service) BaseClient(org.pac4j.core.client.BaseClient) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) HttpServletRequest(javax.servlet.http.HttpServletRequest) ClientCredential(org.apereo.cas.authentication.principal.ClientCredential) CommonProfile(org.pac4j.core.profile.CommonProfile) ExternalContext(org.springframework.webflow.context.ExternalContext) Credentials(org.pac4j.core.credentials.Credentials)

Example 8 with Credentials

use of org.pac4j.core.credentials.Credentials 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 9 with Credentials

use of org.pac4j.core.credentials.Credentials in project cas by apereo.

the class ClientAuthenticationHandlerTests method setUp.

@Before
public void setUp() {
    this.fbClient = new FacebookClient();
    final Clients clients = new Clients(CALLBACK_URL, fbClient);
    this.handler = new ClientAuthenticationHandler("", mock(ServicesManager.class), null, clients);
    this.handler.setTypedIdUsed(true);
    final Credentials credentials = new OAuth20Credentials(null);
    this.clientCredential = new ClientCredential(credentials, fbClient.getName());
    final ServletExternalContext mock = new ServletExternalContext(new MockServletContext(), new MockHttpServletRequest(), new MockHttpServletResponse());
    ExternalContextHolder.setExternalContext(mock);
}
Also used : ClientCredential(org.apereo.cas.authentication.principal.ClientCredential) ServletExternalContext(org.springframework.webflow.context.servlet.ServletExternalContext) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FacebookClient(org.pac4j.oauth.client.FacebookClient) OAuth20Credentials(org.pac4j.oauth.credentials.OAuth20Credentials) Clients(org.pac4j.core.client.Clients) OAuth20Credentials(org.pac4j.oauth.credentials.OAuth20Credentials) Credentials(org.pac4j.core.credentials.Credentials) MockServletContext(org.springframework.mock.web.MockServletContext) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Before(org.junit.Before)

Example 10 with Credentials

use of org.pac4j.core.credentials.Credentials in project cas by apereo.

the class DelegatedClientAuthenticationAction method restoreAuthenticationRequestInContext.

private Service restoreAuthenticationRequestInContext(final RequestContext requestContext, final J2EContext webContext, final String clientName) {
    delegatedSessionCookieManager.restore(webContext);
    final BaseClient<Credentials, CommonProfile> client = (BaseClient<Credentials, CommonProfile>) this.clients.findClient(clientName);
    final Service service = delegatedClientWebflowManager.retrieve(requestContext, webContext, client);
    return service;
}
Also used : CommonProfile(org.pac4j.core.profile.CommonProfile) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) BaseClient(org.pac4j.core.client.BaseClient) Credentials(org.pac4j.core.credentials.Credentials)

Aggregations

Credentials (org.pac4j.core.credentials.Credentials)12 CommonProfile (org.pac4j.core.profile.CommonProfile)7 Client (org.pac4j.core.client.Client)4 Clients (org.pac4j.core.client.Clients)4 WebContext (org.pac4j.core.context.WebContext)4 ClientCredential (org.apereo.cas.authentication.principal.ClientCredential)3 Test (org.junit.Test)3 BaseClient (org.pac4j.core.client.BaseClient)3 HttpAction (org.pac4j.core.exception.HttpAction)3 Optional (java.util.Optional)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)2 Service (org.apereo.cas.authentication.principal.Service)2 WebApplicationService (org.apereo.cas.authentication.principal.WebApplicationService)2 IndirectClient (org.pac4j.core.client.IndirectClient)2 MockWebContext (org.pac4j.core.context.MockWebContext)2 UsernamePasswordCredentials (org.pac4j.core.credentials.UsernamePasswordCredentials)2 UserProfile (org.pac4j.core.profile.UserProfile)2 ImmutableList (com.google.common.collect.ImmutableList)1