Search in sources :

Example 1 with Clients

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

the class DelegatedClientAuthenticationActionTests method verifyStartAuthentication.

@Test
public void verifyStartAuthentication() throws Exception {
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameter(ThemeChangeInterceptor.DEFAULT_PARAM_NAME, MY_THEME);
    mockRequest.setParameter(LocaleChangeInterceptor.DEFAULT_PARAM_NAME, MY_LOCALE);
    mockRequest.setParameter(CasProtocolConstants.PARAMETER_METHOD, MY_METHOD);
    final MockHttpSession mockSession = new MockHttpSession();
    mockRequest.setSession(mockSession);
    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);
    when(servletExternalContext.getNativeResponse()).thenReturn(mockResponse);
    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);
    mockRequestContext.getFlowScope().put(CasProtocolConstants.PARAMETER_SERVICE, RegisteredServiceTestUtils.getService(MY_SERVICE));
    final FacebookClient facebookClient = new FacebookClient(MY_KEY, MY_SECRET);
    final TwitterClient twitterClient = new TwitterClient("3nJPbVTVRZWAyUgoUKQ8UA", "h6LZyZJmcW46Vu8R47MYfeXTSYGI30EqnWaSwVhFkbA");
    final Clients clients = new Clients(MY_LOGIN_URL, facebookClient, twitterClient);
    final DelegatedClientAuthenticationAction action = new DelegatedClientAuthenticationAction(clients, null, mock(CentralAuthenticationService.class), "theme", "locale", false);
    final Event event = action.execute(mockRequestContext);
    assertEquals("error", event.getId());
    assertEquals(MY_THEME, mockSession.getAttribute(ThemeChangeInterceptor.DEFAULT_PARAM_NAME));
    assertEquals(MY_LOCALE, mockSession.getAttribute(LocaleChangeInterceptor.DEFAULT_PARAM_NAME));
    assertEquals(MY_METHOD, mockSession.getAttribute(CasProtocolConstants.PARAMETER_METHOD));
    final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
    final Set<DelegatedClientAuthenticationAction.ProviderLoginPageConfiguration> urls = (Set<DelegatedClientAuthenticationAction.ProviderLoginPageConfiguration>) flowScope.get(DelegatedClientAuthenticationAction.PAC4J_URLS);
    assertFalse(urls.isEmpty());
    assertSame(2, urls.size());
}
Also used : TwitterClient(org.pac4j.oauth.client.TwitterClient) Set(java.util.Set) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) FacebookClient(org.pac4j.oauth.client.FacebookClient) MockRequestContext(org.springframework.webflow.test.MockRequestContext) Clients(org.pac4j.core.client.Clients) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) ServletExternalContext(org.springframework.webflow.context.servlet.ServletExternalContext) MutableAttributeMap(org.springframework.webflow.core.collection.MutableAttributeMap) MockHttpSession(org.springframework.mock.web.MockHttpSession) Event(org.springframework.webflow.execution.Event) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 2 with Clients

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

the class RatpackPac4j method initiateAuthentication.

private static void initiateAuthentication(Context ctx, Class<? extends Client<?, ?>> clientType) {
    Request request = ctx.getRequest();
    Clients clients = ctx.get(Clients.class);
    Client<?, ?> client = clients.findClient(clientType);
    RatpackWebContext.from(ctx, false).then(webContext -> {
        webContext.getSession().set(Pac4jSessionKeys.REQUESTED_URL, request.getUri());
        try {
            client.redirect(webContext, true);
        } catch (Exception e) {
            if (e instanceof RequiresHttpAction) {
                webContext.sendResponse((RequiresHttpAction) e);
                return;
            } else {
                ctx.error(new TechnicalException("Failed to redirect", e));
            }
        }
        webContext.sendResponse();
    });
}
Also used : RequiresHttpAction(org.pac4j.core.exception.RequiresHttpAction) TechnicalException(org.pac4j.core.exception.TechnicalException) Request(ratpack.http.Request) Clients(org.pac4j.core.client.Clients) TechnicalException(org.pac4j.core.exception.TechnicalException)

Example 3 with Clients

use of org.pac4j.core.client.Clients 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 4 with Clients

use of org.pac4j.core.client.Clients 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)

Example 5 with Clients

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

the class DefaultLogoutLogic method perform.

@Override
public R perform(final C context, final Config config, final HttpActionAdapter<R, C> httpActionAdapter, final String defaultUrl, final String inputLogoutUrlPattern, final Boolean inputLocalLogout, final Boolean inputDestroySession, final Boolean inputCentralLogout) {
    logger.debug("=== LOGOUT ===");
    HttpAction action;
    try {
        // default values
        final String logoutUrlPattern;
        if (inputLogoutUrlPattern == null) {
            logoutUrlPattern = Pac4jConstants.DEFAULT_LOGOUT_URL_PATTERN_VALUE;
        } else {
            logoutUrlPattern = inputLogoutUrlPattern;
        }
        final boolean localLogout;
        if (inputLocalLogout == null) {
            localLogout = true;
        } else {
            localLogout = inputLocalLogout;
        }
        final boolean destroySession;
        if (inputDestroySession == null) {
            destroySession = false;
        } else {
            destroySession = inputDestroySession;
        }
        final boolean centralLogout;
        if (inputCentralLogout == null) {
            centralLogout = false;
        } else {
            centralLogout = inputCentralLogout;
        }
        // checks
        assertNotNull("context", context);
        assertNotNull("config", config);
        assertNotNull("httpActionAdapter", httpActionAdapter);
        assertNotBlank(Pac4jConstants.LOGOUT_URL_PATTERN, logoutUrlPattern);
        final Clients configClients = config.getClients();
        assertNotNull("configClients", configClients);
        // logic
        final ProfileManager manager = getProfileManager(context, config);
        final List<CommonProfile> profiles = manager.getAll(true);
        // compute redirection URL
        final String url = context.getRequestParameter(Pac4jConstants.URL);
        String redirectUrl = defaultUrl;
        if (url != null && Pattern.matches(logoutUrlPattern, url)) {
            redirectUrl = url;
        }
        logger.debug("redirectUrl: {}", redirectUrl);
        if (redirectUrl != null) {
            action = HttpAction.redirect(context, redirectUrl);
        } else {
            action = HttpAction.noContent(context);
        }
        // local logout if requested or multiple profiles
        if (localLogout || profiles.size() > 1) {
            logger.debug("Performing application logout");
            manager.logout();
            if (destroySession) {
                final SessionStore sessionStore = context.getSessionStore();
                if (sessionStore != null) {
                    final boolean removed = sessionStore.destroySession(context);
                    if (!removed) {
                        logger.error("Unable to destroy the web session. The session store may not support this feature");
                    }
                } else {
                    logger.error("No session store available for this web context");
                }
            }
        }
        // central logout
        if (centralLogout) {
            logger.debug("Performing central logout");
            for (final CommonProfile profile : profiles) {
                logger.debug("Profile: {}", profile);
                final String clientName = profile.getClientName();
                if (clientName != null) {
                    final Client client = configClients.findClient(clientName);
                    if (client != null) {
                        final String targetUrl;
                        if (redirectUrl != null && (redirectUrl.startsWith(HttpConstants.SCHEME_HTTP) || redirectUrl.startsWith(HttpConstants.SCHEME_HTTPS))) {
                            targetUrl = redirectUrl;
                        } else {
                            targetUrl = null;
                        }
                        final RedirectAction logoutAction = client.getLogoutAction(context, profile, targetUrl);
                        logger.debug("Logout action: {}", logoutAction);
                        if (logoutAction != null) {
                            action = logoutAction.perform(context);
                            break;
                        }
                    }
                }
            }
        }
    } catch (final RuntimeException e) {
        return handleException(e, httpActionAdapter, context);
    }
    return httpActionAdapter.adapt(action.getCode(), context);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) SessionStore(org.pac4j.core.context.session.SessionStore) CommonProfile(org.pac4j.core.profile.CommonProfile) Clients(org.pac4j.core.client.Clients) Client(org.pac4j.core.client.Client) HttpAction(org.pac4j.core.exception.HttpAction) RedirectAction(org.pac4j.core.redirect.RedirectAction)

Aggregations

Clients (org.pac4j.core.client.Clients)33 Test (org.junit.Test)19 CommonProfile (org.pac4j.core.profile.CommonProfile)19 MockIndirectClient (org.pac4j.core.client.MockIndirectClient)16 Client (org.pac4j.core.client.Client)13 WebContext (org.pac4j.core.context.WebContext)10 MockWebContext (org.pac4j.core.context.MockWebContext)7 FacebookClient (org.pac4j.oauth.client.FacebookClient)6 Credentials (org.pac4j.core.credentials.Credentials)5 IndirectClient (org.pac4j.core.client.IndirectClient)4 MockCredentials (org.pac4j.core.credentials.MockCredentials)4 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)4 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)4 ServletExternalContext (org.springframework.webflow.context.servlet.ServletExternalContext)4 LinkedHashMap (java.util.LinkedHashMap)3 List (java.util.List)3 HttpSession (javax.servlet.http.HttpSession)3 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)3 BaseClient (org.pac4j.core.client.BaseClient)3 Config (org.pac4j.core.config.Config)3