Search in sources :

Example 1 with Client

use of org.pac4j.core.client.Client in project ratpack by ratpack.

the class Pac4jAuthenticator method createClients.

private Promise<Clients> createClients(Context ctx, PathBinding pathBinding) throws Exception {
    String boundTo = pathBinding.getBoundTo();
    PublicAddress publicAddress = ctx.get(PublicAddress.class);
    String absoluteCallbackUrl = publicAddress.get(b -> b.maybeEncodedPath(boundTo).maybeEncodedPath(path)).toASCIIString();
    Iterable<? extends Client<?, ?>> result = clientsProvider.get(ctx);
    @SuppressWarnings("rawtypes") List<Client> clients;
    if (result instanceof List) {
        clients = Types.cast(result);
    } else {
        clients = ImmutableList.copyOf(result);
    }
    return Promise.value(new Clients(absoluteCallbackUrl, clients));
}
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) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) PublicAddress(ratpack.server.PublicAddress) Client(org.pac4j.core.client.Client) Clients(org.pac4j.core.client.Clients)

Example 2 with Client

use of org.pac4j.core.client.Client in project cas by apereo.

the class Pac4jServiceTicketValidationAuthorizer method authorize.

@Override
public void authorize(final HttpServletRequest request, final Service service, final Assertion assertion) {
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(service, registeredService);
    LOGGER.debug("Evaluating service [{}] for delegated authentication policy", service);
    final RegisteredServiceDelegatedAuthenticationPolicy policy = registeredService.getAccessStrategy().getDelegatedAuthenticationPolicy();
    if (policy != null) {
        final Map<String, Object> attributes = assertion.getPrimaryAuthentication().getAttributes();
        if (attributes.containsKey(ClientCredential.AUTHENTICATION_ATTRIBUTE_CLIENT_NAME)) {
            final Object clientNameAttr = attributes.get(ClientCredential.AUTHENTICATION_ATTRIBUTE_CLIENT_NAME);
            final Optional<Object> value = CollectionUtils.firstElement(clientNameAttr);
            if (value.isPresent()) {
                final String client = value.get().toString();
                LOGGER.debug("Evaluating delegated authentication policy [{}] for client [{}] and service [{}]", policy, client, registeredService);
                final AuditableContext context = AuditableContext.builder().registeredService(registeredService).properties(CollectionUtils.wrap(Client.class.getSimpleName(), client)).build();
                final AuditableExecutionResult result = delegatedAuthenticationPolicyEnforcer.execute(context);
                result.throwExceptionIfNeeded();
            }
        }
    }
}
Also used : AuditableContext(org.apereo.cas.audit.AuditableContext) RegisteredService(org.apereo.cas.services.RegisteredService) RegisteredServiceDelegatedAuthenticationPolicy(org.apereo.cas.services.RegisteredServiceDelegatedAuthenticationPolicy) Client(org.pac4j.core.client.Client) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult)

Example 3 with Client

use of org.pac4j.core.client.Client in project cas by apereo.

the class ClientAuthenticationHandler method doAuthentication.

@Override
protected AuthenticationHandlerExecutionResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    try {
        final ClientCredential clientCredentials = (ClientCredential) credential;
        LOGGER.debug("Located client credentials as [{}]", clientCredentials);
        final Credentials credentials = clientCredentials.getCredentials();
        LOGGER.debug("Client name: [{}]", clientCredentials.getClientName());
        // get client
        final Client client = this.clients.findClient(clientCredentials.getClientName());
        LOGGER.debug("Delegated client is: [{}]", client);
        final HttpServletRequest request = WebUtils.getHttpServletRequestFromExternalWebflowContext();
        final HttpServletResponse response = WebUtils.getHttpServletResponseFromExternalWebflowContext();
        final WebContext webContext = Pac4jUtils.getPac4jJ2EContext(request, response);
        final UserProfile userProfile = client.getUserProfile(credentials, webContext);
        LOGGER.debug("Final user profile is: [{}]", userProfile);
        return createResult(clientCredentials, userProfile);
    } catch (final HttpAction e) {
        throw new PreventedException(e);
    }
}
Also used : ClientCredential(org.apereo.cas.authentication.principal.ClientCredential) HttpServletRequest(javax.servlet.http.HttpServletRequest) WebContext(org.pac4j.core.context.WebContext) UserProfile(org.pac4j.core.profile.UserProfile) HttpServletResponse(javax.servlet.http.HttpServletResponse) PreventedException(org.apereo.cas.authentication.PreventedException) Client(org.pac4j.core.client.Client) Credentials(org.pac4j.core.credentials.Credentials) HttpAction(org.pac4j.core.exception.HttpAction)

Example 4 with Client

use of org.pac4j.core.client.Client in project knox by apache.

the class Pac4jDispatcherFilter method init.

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // JWT service
    final ServletContext context = filterConfig.getServletContext();
    CryptoService cryptoService = null;
    String clusterName = null;
    if (context != null) {
        GatewayServices services = (GatewayServices) context.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
        clusterName = (String) context.getAttribute(GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE);
        if (services != null) {
            keystoreService = (KeystoreService) services.getService(GatewayServices.KEYSTORE_SERVICE);
            cryptoService = (CryptoService) services.getService(GatewayServices.CRYPTO_SERVICE);
            aliasService = (AliasService) services.getService(GatewayServices.ALIAS_SERVICE);
            masterService = (MasterService) services.getService("MasterService");
        }
    }
    // crypto service, alias service and cluster name are mandatory
    if (cryptoService == null || aliasService == null || clusterName == null) {
        log.cryptoServiceAndAliasServiceAndClusterNameRequired();
        throw new ServletException("The crypto service, alias service and cluster name are required.");
    }
    try {
        aliasService.getPasswordFromAliasForCluster(clusterName, KnoxSessionStore.PAC4J_PASSWORD, true);
    } catch (AliasServiceException e) {
        log.unableToGenerateAPasswordForEncryption(e);
        throw new ServletException("Unable to generate a password for encryption.");
    }
    // url to SSO authentication provider
    String pac4jCallbackUrl = filterConfig.getInitParameter(PAC4J_CALLBACK_URL);
    if (pac4jCallbackUrl == null) {
        log.ssoAuthenticationProviderUrlRequired();
        throw new ServletException("Required pac4j callback URL is missing.");
    }
    // add the callback parameter to know it's a callback
    pac4jCallbackUrl = CommonHelper.addParameter(pac4jCallbackUrl, PAC4J_CALLBACK_PARAMETER, "true");
    final Config config;
    final String clientName;
    // client name from servlet parameter (mandatory)
    final String clientNameParameter = filterConfig.getInitParameter("clientName");
    if (clientNameParameter == null) {
        log.clientNameParameterRequired();
        throw new ServletException("Required pac4j clientName parameter is missing.");
    }
    if (TEST_BASIC_AUTH.equalsIgnoreCase(clientNameParameter)) {
        // test configuration
        final IndirectBasicAuthClient indirectBasicAuthClient = new IndirectBasicAuthClient(new SimpleTestUsernamePasswordAuthenticator());
        indirectBasicAuthClient.setRealmName("Knox TEST");
        config = new Config(pac4jCallbackUrl, indirectBasicAuthClient);
        clientName = "IndirectBasicAuthClient";
    } else {
        // get clients from the init parameters
        final Map<String, String> properties = new HashMap<>();
        final Enumeration<String> names = filterConfig.getInitParameterNames();
        addDefaultConfig(clientNameParameter, properties);
        while (names.hasMoreElements()) {
            final String key = names.nextElement();
            properties.put(key, filterConfig.getInitParameter(key));
        }
        final PropertiesConfigFactory propertiesConfigFactory = new PropertiesConfigFactory(pac4jCallbackUrl, properties);
        config = propertiesConfigFactory.build();
        final List<Client> clients = config.getClients().getClients();
        if (clients == null || clients.size() == 0) {
            log.atLeastOnePac4jClientMustBeDefined();
            throw new ServletException("At least one pac4j client must be defined.");
        }
        if (CommonHelper.isBlank(clientNameParameter)) {
            clientName = clients.get(0).getName();
        } else {
            clientName = clientNameParameter;
        }
    }
    callbackFilter = new CallbackFilter();
    callbackFilter.init(filterConfig);
    callbackFilter.setConfigOnly(config);
    securityFilter = new SecurityFilter();
    securityFilter.setClients(clientName);
    securityFilter.setConfigOnly(config);
    final String domainSuffix = filterConfig.getInitParameter(PAC4J_COOKIE_DOMAIN_SUFFIX_PARAM);
    final String sessionStoreVar = filterConfig.getInitParameter(PAC4J_SESSION_STORE);
    SessionStore sessionStore;
    if (!StringUtils.isBlank(sessionStoreVar) && J2ESessionStore.class.getName().contains(sessionStoreVar)) {
        sessionStore = new J2ESessionStore();
    } else {
        sessionStore = new KnoxSessionStore(cryptoService, clusterName, domainSuffix);
    }
    config.setSessionStore(sessionStore);
}
Also used : GatewayServices(org.apache.knox.gateway.services.GatewayServices) J2ESessionStore(org.pac4j.core.context.session.J2ESessionStore) KnoxSessionStore(org.apache.knox.gateway.pac4j.session.KnoxSessionStore) HashMap(java.util.HashMap) Config(org.pac4j.core.config.Config) AliasServiceException(org.apache.knox.gateway.services.security.AliasServiceException) KnoxSessionStore(org.apache.knox.gateway.pac4j.session.KnoxSessionStore) SessionStore(org.pac4j.core.context.session.SessionStore) J2ESessionStore(org.pac4j.core.context.session.J2ESessionStore) CryptoService(org.apache.knox.gateway.services.security.CryptoService) PropertiesConfigFactory(org.pac4j.config.client.PropertiesConfigFactory) SecurityFilter(org.pac4j.j2e.filter.SecurityFilter) CallbackFilter(org.pac4j.j2e.filter.CallbackFilter) Client(org.pac4j.core.client.Client) IndirectBasicAuthClient(org.pac4j.http.client.indirect.IndirectBasicAuthClient) IndirectBasicAuthClient(org.pac4j.http.client.indirect.IndirectBasicAuthClient) SimpleTestUsernamePasswordAuthenticator(org.pac4j.http.credentials.authenticator.test.SimpleTestUsernamePasswordAuthenticator)

Example 5 with Client

use of org.pac4j.core.client.Client in project pac4j by pac4j.

the class DefaultCallbackLogic method perform.

@Override
public R perform(final C context, final Config config, final HttpActionAdapter<R, C> httpActionAdapter, final String inputDefaultUrl, final Boolean inputSaveInSession, final Boolean inputMultiProfile, final Boolean inputRenewSession, final String client) {
    logger.debug("=== CALLBACK ===");
    HttpAction action;
    try {
        // default values
        final String defaultUrl;
        if (inputDefaultUrl == null) {
            defaultUrl = Pac4jConstants.DEFAULT_URL_VALUE;
        } else {
            defaultUrl = inputDefaultUrl;
        }
        final boolean saveInSession;
        if (inputSaveInSession == null) {
            saveInSession = true;
        } else {
            saveInSession = inputSaveInSession;
        }
        final boolean multiProfile;
        if (inputMultiProfile == null) {
            multiProfile = false;
        } else {
            multiProfile = inputMultiProfile;
        }
        final boolean renewSession;
        if (inputRenewSession == null) {
            renewSession = true;
        } else {
            renewSession = inputRenewSession;
        }
        // checks
        assertNotNull("clientFinder", clientFinder);
        assertNotNull("context", context);
        assertNotNull("config", config);
        assertNotNull("httpActionAdapter", httpActionAdapter);
        assertNotBlank(Pac4jConstants.DEFAULT_URL, defaultUrl);
        final Clients clients = config.getClients();
        assertNotNull("clients", clients);
        // logic
        final List<Client> foundClients = clientFinder.find(clients, context, client);
        assertTrue(foundClients != null && foundClients.size() == 1, "unable to find one indirect client for the callback: check the callback URL for a client name parameter or suffix path" + " or ensure that your configuration defaults to one indirect client");
        final Client foundClient = foundClients.get(0);
        logger.debug("foundClient: {}", foundClient);
        assertNotNull("foundClient", foundClient);
        final Credentials credentials = foundClient.getCredentials(context);
        logger.debug("credentials: {}", credentials);
        final CommonProfile profile = foundClient.getUserProfile(credentials, context);
        logger.debug("profile: {}", profile);
        saveUserProfile(context, config, profile, saveInSession, multiProfile, renewSession);
        action = redirectToOriginallyRequestedUrl(context, defaultUrl);
    } catch (final RuntimeException e) {
        return handleException(e, httpActionAdapter, context);
    }
    return httpActionAdapter.adapt(action.getCode(), context);
}
Also used : CommonProfile(org.pac4j.core.profile.CommonProfile) Clients(org.pac4j.core.client.Clients) BaseClient(org.pac4j.core.client.BaseClient) Client(org.pac4j.core.client.Client) HttpAction(org.pac4j.core.exception.HttpAction) Credentials(org.pac4j.core.credentials.Credentials)

Aggregations

Client (org.pac4j.core.client.Client)25 Clients (org.pac4j.core.client.Clients)14 CommonProfile (org.pac4j.core.profile.CommonProfile)9 WebContext (org.pac4j.core.context.WebContext)8 MockIndirectClient (org.pac4j.core.client.MockIndirectClient)7 lombok.val (lombok.val)6 Test (org.junit.Test)5 Credentials (org.pac4j.core.credentials.Credentials)5 List (java.util.List)4 Optional (java.util.Optional)4 IndirectClient (org.pac4j.core.client.IndirectClient)4 HttpAction (org.pac4j.core.exception.HttpAction)4 UserProfile (org.pac4j.core.profile.UserProfile)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Slf4j (lombok.extern.slf4j.Slf4j)3 SessionStore (org.pac4j.core.context.session.SessionStore)3 ProfileManager (org.pac4j.core.profile.ProfileManager)3 ImmutableList (com.google.common.collect.ImmutableList)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2