Search in sources :

Example 91 with Service

use of org.apereo.cas.authentication.principal.Service 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 92 with Service

use of org.apereo.cas.authentication.principal.Service 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 93 with Service

use of org.apereo.cas.authentication.principal.Service in project cas by apereo.

the class OAuth20AccessTokenControllerTests method addRefreshToken.

private RefreshToken addRefreshToken(final Principal principal, final RegisteredService registeredService) {
    final Authentication authentication = getAuthentication(principal);
    final WebApplicationServiceFactory factory = new WebApplicationServiceFactory();
    final Service service = factory.createService(registeredService.getServiceId());
    final RefreshToken refreshToken = oAuthRefreshTokenFactory.create(service, authentication);
    oAuth20AccessTokenController.getTicketRegistry().addTicket(refreshToken);
    return refreshToken;
}
Also used : RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) Authentication(org.apereo.cas.authentication.Authentication) WebApplicationServiceFactory(org.apereo.cas.authentication.principal.WebApplicationServiceFactory) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service)

Example 94 with Service

use of org.apereo.cas.authentication.principal.Service in project cas by apereo.

the class WsFederationAction method doExecute.

/**
     * Executes the webflow action.
     *
     * @param context the context
     * @return the event
     * @throws Exception all unhandled exceptions
     */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    try {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        final HttpSession session = request.getSession();
        final String wa = request.getParameter(WA);
        // it's an authentication
        if (StringUtils.isNotBlank(wa) && wa.equalsIgnoreCase(WSIGNIN)) {
            final String wResult = request.getParameter(WRESULT);
            LOGGER.debug("Parameter [{}] received: [{}]", WRESULT, wResult);
            if (StringUtils.isBlank(wResult)) {
                LOGGER.error("No [{}] parameter is found", WRESULT);
                return error();
            }
            // create credentials
            LOGGER.debug("Attempting to create an assertion from the token parameter");
            final Assertion assertion = this.wsFederationHelper.parseTokenFromString(wResult, configuration);
            if (assertion == null) {
                LOGGER.error("Could not validate assertion via parsing the token from [{}]", WRESULT);
                return error();
            }
            LOGGER.debug("Attempting to validate the signature on the assertion");
            if (!this.wsFederationHelper.validateSignature(assertion, this.configuration)) {
                LOGGER.error("WS Requested Security Token is blank or the signature is not valid.");
                return error();
            }
            try {
                final Service service = (Service) session.getAttribute(SERVICE);
                LOGGER.debug("Creating credential based on the provided assertion");
                final WsFederationCredential credential = this.wsFederationHelper.createCredentialFromToken(assertion);
                final String rpId = getRelyingPartyIdentifier(service);
                if (credential != null && credential.isValid(rpId, this.configuration.getIdentityProviderIdentifier(), this.configuration.getTolerance())) {
                    LOGGER.debug("Validated assertion for the created credential successfully");
                    if (this.configuration.getAttributeMutator() != null) {
                        LOGGER.debug("Modifying credential attributes based on [{}]", this.configuration.getAttributeMutator().getClass().getSimpleName());
                        this.configuration.getAttributeMutator().modifyAttributes(credential.getAttributes());
                    }
                } else {
                    LOGGER.warn("SAML assertions are blank or no longer valid based on RP identifier [{}] and IdP identifier [{}]", rpId, this.configuration.getIdentityProviderIdentifier());
                    final String url = authorizationUrl + rpId;
                    context.getFlowScope().put(PROVIDERURL, url);
                    LOGGER.warn("Created authentication url [{}] and returning error", url);
                    return error();
                }
                context.getFlowScope().put(SERVICE, service);
                restoreRequestAttribute(request, session, THEME);
                restoreRequestAttribute(request, session, LOCALE);
                restoreRequestAttribute(request, session, METHOD);
                LOGGER.debug("Creating final authentication result based on the given credential");
                final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, credential);
                LOGGER.debug("Attempting to create a ticket-granting ticket for the authentication result");
                WebUtils.putTicketGrantingTicketInScopes(context, this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult));
                LOGGER.info("Token validated and new [{}] created: [{}]", credential.getClass().getName(), credential);
                return success();
            } catch (final AbstractTicketException e) {
                LOGGER.error(e.getMessage(), e);
                return error();
            }
        } else {
            // no authentication : go to login page. save parameters in web session
            final Service service = (Service) context.getFlowScope().get(SERVICE);
            if (service != null) {
                session.setAttribute(SERVICE, service);
            }
            saveRequestParameter(request, session, THEME);
            saveRequestParameter(request, session, LOCALE);
            saveRequestParameter(request, session, METHOD);
            final String url = authorizationUrl + getRelyingPartyIdentifier(service);
            LOGGER.info("Preparing to redirect to the IdP [{}]", url);
            context.getFlowScope().put(PROVIDERURL, url);
        }
        LOGGER.debug("Returning error event");
        return error();
    } catch (final Exception ex) {
        LOGGER.error(ex.getMessage(), ex);
        return error();
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSession(javax.servlet.http.HttpSession) Assertion(org.opensaml.saml.saml1.core.Assertion) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Example 95 with Service

use of org.apereo.cas.authentication.principal.Service in project cas by apereo.

the class DistributedTicketRegistryTests method verifyDeleteTicketWithPGT.

@Test
public void verifyDeleteTicketWithPGT() {
    final Authentication a = CoreAuthenticationTestUtils.getAuthentication();
    this.ticketRegistry.addTicket(new TicketGrantingTicketImpl(TGT_NAME, a, new NeverExpiresExpirationPolicy()));
    final TicketGrantingTicket tgt = this.ticketRegistry.getTicket(TGT_NAME, TicketGrantingTicket.class);
    final Service service = CoreAuthenticationTestUtils.getService("TGT_DELETE_TEST");
    final ServiceTicket st1 = tgt.grantServiceTicket("ST1", service, new NeverExpiresExpirationPolicy(), true, true);
    this.ticketRegistry.addTicket(st1);
    assertNotNull(this.ticketRegistry.getTicket(TGT_NAME, TicketGrantingTicket.class));
    assertNotNull(this.ticketRegistry.getTicket("ST1", ServiceTicket.class));
    final ProxyGrantingTicket pgt = st1.grantProxyGrantingTicket("PGT-1", a, new NeverExpiresExpirationPolicy());
    assertEquals(a, pgt.getAuthentication());
    this.ticketRegistry.addTicket(pgt);
    assertSame(3, this.ticketRegistry.deleteTicket(tgt.getId()));
    assertNull(this.ticketRegistry.getTicket(TGT_NAME, TicketGrantingTicket.class));
    assertNull(this.ticketRegistry.getTicket("ST1", ServiceTicket.class));
    assertNull(this.ticketRegistry.getTicket("PGT-1", ProxyGrantingTicket.class));
}
Also used : NeverExpiresExpirationPolicy(org.apereo.cas.ticket.support.NeverExpiresExpirationPolicy) Authentication(org.apereo.cas.authentication.Authentication) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) Service(org.apereo.cas.authentication.principal.Service) TicketGrantingTicketImpl(org.apereo.cas.ticket.TicketGrantingTicketImpl) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) ProxyGrantingTicket(org.apereo.cas.ticket.proxy.ProxyGrantingTicket) Test(org.junit.Test)

Aggregations

Service (org.apereo.cas.authentication.principal.Service)173 RegisteredService (org.apereo.cas.services.RegisteredService)67 Test (org.junit.Test)61 Authentication (org.apereo.cas.authentication.Authentication)47 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)44 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)42 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)35 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)32 WebApplicationService (org.apereo.cas.authentication.principal.WebApplicationService)29 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)21 AbstractWebApplicationService (org.apereo.cas.authentication.principal.AbstractWebApplicationService)18 HttpServletRequest (javax.servlet.http.HttpServletRequest)16 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)15 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)15 Credential (org.apereo.cas.authentication.Credential)13 Principal (org.apereo.cas.authentication.principal.Principal)13 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)13 MockTicketGrantingTicket (org.apereo.cas.mock.MockTicketGrantingTicket)12 TicketGrantingTicketImpl (org.apereo.cas.ticket.TicketGrantingTicketImpl)12 NeverExpiresExpirationPolicy (org.apereo.cas.ticket.support.NeverExpiresExpirationPolicy)12