Search in sources :

Example 16 with Clients

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

the class DelegatedClientAuthenticationActionTests method verifyFinishAuthentication.

@Test
public void verifyFinishAuthentication() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "FacebookClient");
    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.setAttribute(ThemeChangeInterceptor.DEFAULT_PARAM_NAME, MY_THEME);
    mockSession.setAttribute(LocaleChangeInterceptor.DEFAULT_PARAM_NAME, MY_LOCALE);
    mockSession.setAttribute(CasProtocolConstants.PARAMETER_METHOD, MY_METHOD);
    final Service service = CoreAuthenticationTestUtils.getService(MY_SERVICE);
    mockSession.setAttribute(CasProtocolConstants.PARAMETER_SERVICE, service);
    mockRequest.setSession(mockSession);
    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);
    when(servletExternalContext.getNativeResponse()).thenReturn(new MockHttpServletResponse());
    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);
    final FacebookClient facebookClient = new FacebookClient() {

        @Override
        protected OAuth20Credentials retrieveCredentials(final WebContext context) throws HttpAction {
            return new OAuth20Credentials("fakeVerifier", FacebookClient.class.getSimpleName());
        }
    };
    facebookClient.setName(FacebookClient.class.getSimpleName());
    final Clients clients = new Clients(MY_LOGIN_URL, facebookClient);
    final TicketGrantingTicket tgt = new TicketGrantingTicketImpl(TGT_ID, mock(Authentication.class), mock(ExpirationPolicy.class));
    final CentralAuthenticationService casImpl = mock(CentralAuthenticationService.class);
    when(casImpl.createTicketGrantingTicket(any(AuthenticationResult.class))).thenReturn(tgt);
    final AuthenticationTransactionManager transManager = mock(AuthenticationTransactionManager.class);
    final AuthenticationManager authNManager = mock(AuthenticationManager.class);
    when(authNManager.authenticate(any(AuthenticationTransaction.class))).thenReturn(CoreAuthenticationTestUtils.getAuthentication());
    when(transManager.getAuthenticationManager()).thenReturn(authNManager);
    when(transManager.handle(any(AuthenticationTransaction.class), any(AuthenticationResultBuilder.class))).thenReturn(transManager);
    final AuthenticationSystemSupport support = mock(AuthenticationSystemSupport.class);
    when(support.getAuthenticationTransactionManager()).thenReturn(transManager);
    final DelegatedClientAuthenticationAction action = new DelegatedClientAuthenticationAction(clients, support, casImpl, "theme", "locale", false);
    final Event event = action.execute(mockRequestContext);
    assertEquals("success", event.getId());
    assertEquals(MY_THEME, mockRequest.getAttribute(ThemeChangeInterceptor.DEFAULT_PARAM_NAME));
    assertEquals(MY_LOCALE, mockRequest.getAttribute(LocaleChangeInterceptor.DEFAULT_PARAM_NAME));
    assertEquals(MY_METHOD, mockRequest.getAttribute(CasProtocolConstants.PARAMETER_METHOD));
    assertEquals(MY_SERVICE, mockRequest.getAttribute(CasProtocolConstants.PARAMETER_SERVICE));
    final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
    final MutableAttributeMap requestScope = mockRequestContext.getRequestScope();
    assertEquals(service, flowScope.get(CasProtocolConstants.PARAMETER_SERVICE));
    assertEquals(TGT_ID, flowScope.get(TGT_NAME));
    assertEquals(TGT_ID, requestScope.get(TGT_NAME));
}
Also used : WebContext(org.pac4j.core.context.WebContext) AuthenticationSystemSupport(org.apereo.cas.authentication.AuthenticationSystemSupport) AuthenticationTransactionManager(org.apereo.cas.authentication.AuthenticationTransactionManager) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) FacebookClient(org.pac4j.oauth.client.FacebookClient) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) Service(org.apereo.cas.authentication.principal.Service) MockRequestContext(org.springframework.webflow.test.MockRequestContext) Clients(org.pac4j.core.client.Clients) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) ExpirationPolicy(org.apereo.cas.ticket.ExpirationPolicy) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) AuthenticationManager(org.apereo.cas.authentication.AuthenticationManager) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) ServletExternalContext(org.springframework.webflow.context.servlet.ServletExternalContext) Authentication(org.apereo.cas.authentication.Authentication) OAuth20Credentials(org.pac4j.oauth.credentials.OAuth20Credentials) MutableAttributeMap(org.springframework.webflow.core.collection.MutableAttributeMap) MockHttpSession(org.springframework.mock.web.MockHttpSession) Event(org.springframework.webflow.execution.Event) TicketGrantingTicketImpl(org.apereo.cas.ticket.TicketGrantingTicketImpl) AuthenticationTransaction(org.apereo.cas.authentication.AuthenticationTransaction) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 17 with Clients

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

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

the class CasConsentReviewConfiguration method casConsentPac4jConfig.

@Bean
@RefreshScope
public Config casConsentPac4jConfig() {
    final CasConfiguration conf = new CasConfiguration(casProperties.getServer().getLoginUrl());
    final CasClient client = new CasClient(conf);
    client.setName(CAS_CONSENT_CLIENT);
    client.setCallbackUrl(casProperties.getServer().getPrefix().concat("/consentReview/callback"));
    client.setAuthorizationGenerator(new DefaultCasAuthorizationGenerator<>());
    final Clients clients = new Clients(client);
    final Config config = new Config(clients);
    config.setAuthorizer(new IsAuthenticatedAuthorizer());
    config.setCallbackLogic(new DefaultCallbackLogic());
    config.setLogoutLogic(new DefaultLogoutLogic());
    // get role authorizer from admin pages for smooth integration
    final Map<String, Authorizer> adminAuthorizers = casAdminPagesPac4jConfig.getAuthorizers();
    final String auth = RequireAnyRoleAuthorizer.class.getSimpleName();
    if (adminAuthorizers.containsKey(auth)) {
        config.addAuthorizer(auth, adminAuthorizers.get(auth));
        final BaseClient adminClient = casAdminPagesPac4jConfig.getClients().findClient(DirectCasClient.class);
        client.addAuthorizationGenerators(adminClient.getAuthorizationGenerators());
    }
    return config;
}
Also used : IsAuthenticatedAuthorizer(org.pac4j.core.authorization.authorizer.IsAuthenticatedAuthorizer) CasConfiguration(org.pac4j.cas.config.CasConfiguration) Config(org.pac4j.core.config.Config) RequireAnyRoleAuthorizer(org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer) IsAuthenticatedAuthorizer(org.pac4j.core.authorization.authorizer.IsAuthenticatedAuthorizer) Authorizer(org.pac4j.core.authorization.authorizer.Authorizer) Clients(org.pac4j.core.client.Clients) DefaultLogoutLogic(org.pac4j.core.engine.DefaultLogoutLogic) DefaultCallbackLogic(org.pac4j.core.engine.DefaultCallbackLogic) BaseClient(org.pac4j.core.client.BaseClient) CasClient(org.pac4j.cas.client.CasClient) DirectCasClient(org.pac4j.cas.client.direct.DirectCasClient) RefreshScope(org.springframework.cloud.context.config.annotation.RefreshScope) ConditionalOnBean(org.springframework.boot.autoconfigure.condition.ConditionalOnBean) Bean(org.springframework.context.annotation.Bean)

Example 19 with Clients

use of org.pac4j.core.client.Clients 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 20 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 ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);
    when(servletExternalContext.getNativeResponse()).thenReturn(mockResponse);
    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);
    final Service service = RegisteredServiceTestUtils.getService(MY_SERVICE);
    mockRequestContext.getFlowScope().put(CasProtocolConstants.PARAMETER_SERVICE, 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 AuditableExecution enforcer = mock(AuditableExecution.class);
    when(enforcer.execute(any())).thenReturn(new AuditableExecutionResult());
    final DefaultTicketRegistry ticketRegistry = new DefaultTicketRegistry();
    final DelegatedClientWebflowManager manager = new DelegatedClientWebflowManager(ticketRegistry, new DefaultTransientSessionTicketFactory(new HardTimeoutExpirationPolicy(60)), ThemeChangeInterceptor.DEFAULT_PARAM_NAME, LocaleChangeInterceptor.DEFAULT_PARAM_NAME, new WebApplicationServiceFactory(), "https://cas.example.org", new DefaultAuthenticationServiceSelectionPlan(new DefaultAuthenticationServiceSelectionStrategy()));
    final Ticket ticket = manager.store(Pac4jUtils.getPac4jJ2EContext(mockRequest, new MockHttpServletResponse()), facebookClient);
    mockRequest.addParameter(DelegatedClientWebflowManager.PARAMETER_CLIENT_ID, ticket.getId());
    final DelegatedClientAuthenticationAction action = new DelegatedClientAuthenticationAction(clients, null, mock(CentralAuthenticationService.class), getServicesManagerWith(service, facebookClient), enforcer, manager, new DelegatedSessionCookieManager(mock(CookieRetrievingCookieGenerator.class)));
    final Event event = action.execute(mockRequestContext);
    assertEquals("error", event.getId());
    manager.retrieve(mockRequestContext, Pac4jUtils.getPac4jJ2EContext(mockRequest, new MockHttpServletResponse()), facebookClient);
    assertEquals(MY_THEME, mockRequest.getAttribute(ThemeChangeInterceptor.DEFAULT_PARAM_NAME));
    assertEquals(MY_LOCALE, mockRequest.getAttribute(LocaleChangeInterceptor.DEFAULT_PARAM_NAME));
    assertEquals(MY_METHOD, mockRequest.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) FacebookClient(org.pac4j.oauth.client.FacebookClient) DefaultAuthenticationServiceSelectionPlan(org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionPlan) DefaultTransientSessionTicketFactory(org.apereo.cas.ticket.factory.DefaultTransientSessionTicketFactory) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) DefaultTicketRegistry(org.apereo.cas.ticket.registry.DefaultTicketRegistry) WebApplicationServiceFactory(org.apereo.cas.authentication.principal.WebApplicationServiceFactory) MutableAttributeMap(org.springframework.webflow.core.collection.MutableAttributeMap) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) DefaultAuthenticationServiceSelectionStrategy(org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionStrategy) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) Ticket(org.apereo.cas.ticket.Ticket) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HardTimeoutExpirationPolicy(org.apereo.cas.ticket.support.HardTimeoutExpirationPolicy) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) AbstractRegisteredService(org.apereo.cas.services.AbstractRegisteredService) Service(org.apereo.cas.authentication.principal.Service) MockRequestContext(org.springframework.webflow.test.MockRequestContext) Clients(org.pac4j.core.client.Clients) AuditableExecution(org.apereo.cas.audit.AuditableExecution) DelegatedClientWebflowManager(org.apereo.cas.web.DelegatedClientWebflowManager) DelegatedSessionCookieManager(org.apereo.cas.web.pac4j.DelegatedSessionCookieManager) ServletExternalContext(org.springframework.webflow.context.servlet.ServletExternalContext) Event(org.springframework.webflow.execution.Event) Test(org.junit.Test)

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