Search in sources :

Example 1 with AuditableExecutionResult

use of org.apereo.cas.audit.AuditableExecutionResult 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 2 with AuditableExecutionResult

use of org.apereo.cas.audit.AuditableExecutionResult in project cas by apereo.

the class DelegatedClientAuthenticationActionTests method verifyFinishAuthentication.

@Test
public void verifyFinishAuthentication() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameter(Pac4jConstants.DEFAULT_CLIENT_NAME_PARAMETER, "FacebookClient");
    mockRequest.addParameter(ThemeChangeInterceptor.DEFAULT_PARAM_NAME, MY_THEME);
    mockRequest.addParameter(LocaleChangeInterceptor.DEFAULT_PARAM_NAME, MY_LOCALE);
    mockRequest.addParameter(CasProtocolConstants.PARAMETER_METHOD, MY_METHOD);
    final Service service = CoreAuthenticationTestUtils.getService(MY_SERVICE);
    mockRequest.addParameter(CasProtocolConstants.PARAMETER_SERVICE, service.getId());
    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) {
            return new OAuth20Credentials("fakeVerifier");
        }
    };
    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())).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 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, support, casImpl, getServicesManagerWith(service, facebookClient), enforcer, manager, new DelegatedSessionCookieManager(mock(CookieRetrievingCookieGenerator.class)));
    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.getId(), ((Service) flowScope.get(CasProtocolConstants.PARAMETER_SERVICE)).getId());
    assertEquals(TGT_ID, flowScope.get(WebUtils.PARAMETER_TICKET_GRANTING_TICKET_ID));
    assertEquals(TGT_ID, requestScope.get(WebUtils.PARAMETER_TICKET_GRANTING_TICKET_ID));
}
Also used : WebContext(org.pac4j.core.context.WebContext) FacebookClient(org.pac4j.oauth.client.FacebookClient) DefaultAuthenticationServiceSelectionPlan(org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionPlan) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) DefaultTransientSessionTicketFactory(org.apereo.cas.ticket.factory.DefaultTransientSessionTicketFactory) HardTimeoutExpirationPolicy(org.apereo.cas.ticket.support.HardTimeoutExpirationPolicy) ExpirationPolicy(org.apereo.cas.ticket.ExpirationPolicy) 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) TicketGrantingTicketImpl(org.apereo.cas.ticket.TicketGrantingTicketImpl) AuthenticationTransaction(org.apereo.cas.authentication.AuthenticationTransaction) 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) AuthenticationSystemSupport(org.apereo.cas.authentication.AuthenticationSystemSupport) AuthenticationTransactionManager(org.apereo.cas.authentication.AuthenticationTransactionManager) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) 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) AuthenticationManager(org.apereo.cas.authentication.AuthenticationManager) DelegatedSessionCookieManager(org.apereo.cas.web.pac4j.DelegatedSessionCookieManager) ServletExternalContext(org.springframework.webflow.context.servlet.ServletExternalContext) Authentication(org.apereo.cas.authentication.Authentication) OAuth20Credentials(org.pac4j.oauth.credentials.OAuth20Credentials) Event(org.springframework.webflow.execution.Event) Test(org.junit.Test)

Example 3 with AuditableExecutionResult

use of org.apereo.cas.audit.AuditableExecutionResult in project cas by apereo.

the class OAuth20AuthorizeEndpointController method redirectToCallbackRedirectUrl.

/**
 * Redirect to callback redirect url model and view.
 *
 * @param manager           the manager
 * @param registeredService the registered service
 * @param context           the context
 * @param clientId          the client id
 * @return the model and view
 */
protected ModelAndView redirectToCallbackRedirectUrl(final ProfileManager manager, final OAuthRegisteredService registeredService, final J2EContext context, final String clientId) {
    final Optional<UserProfile> profile = manager.get(true);
    if (profile == null || !profile.isPresent()) {
        LOGGER.error("Unexpected null profile from profile manager. Request is not fully authenticated.");
        return OAuth20Utils.produceUnauthorizedErrorView();
    }
    final Service service = this.authenticationBuilder.buildService(registeredService, context, false);
    LOGGER.debug("Created service [{}] based on registered service [{}]", service, registeredService);
    final Authentication authentication = this.authenticationBuilder.build(profile.get(), registeredService, context, service);
    LOGGER.debug("Created OAuth authentication [{}] for service [{}]", service, authentication);
    try {
        final AuditableContext audit = AuditableContext.builder().service(service).authentication(authentication).registeredService(registeredService).retrievePrincipalAttributesFromReleasePolicy(Boolean.TRUE).build();
        final AuditableExecutionResult accessResult = this.registeredServiceAccessStrategyEnforcer.execute(audit);
        accessResult.throwExceptionIfNeeded();
    } catch (final UnauthorizedServiceException | PrincipalException e) {
        LOGGER.error(e.getMessage(), e);
        return OAuth20Utils.produceUnauthorizedErrorView();
    }
    final View view = buildAuthorizationForRequest(registeredService, context, clientId, service, authentication);
    if (view != null) {
        return OAuth20Utils.redirectTo(view);
    }
    LOGGER.debug("No explicit view was defined as part of the authorization response");
    return null;
}
Also used : AuditableContext(org.apereo.cas.audit.AuditableContext) UserProfile(org.pac4j.core.profile.UserProfile) Authentication(org.apereo.cas.authentication.Authentication) PrincipalException(org.apereo.cas.authentication.PrincipalException) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) Service(org.apereo.cas.authentication.principal.Service) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View)

Example 4 with AuditableExecutionResult

use of org.apereo.cas.audit.AuditableExecutionResult in project cas by apereo.

the class AccessTokenPasswordGrantRequestExtractor method extract.

@Override
public AccessTokenRequestDataHolder extract(final HttpServletRequest request, final HttpServletResponse response) {
    final String clientId = request.getParameter(OAuth20Constants.CLIENT_ID);
    final Set<String> scopes = OAuth20Utils.parseRequestScopes(request);
    LOGGER.debug("Locating OAuth registered service by client id [{}]", clientId);
    final OAuthRegisteredService registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(this.servicesManager, clientId);
    LOGGER.debug("Located OAuth registered service [{}]", registeredService);
    final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
    final ProfileManager manager = Pac4jUtils.getPac4jProfileManager(request, response);
    final Optional<UserProfile> profile = manager.get(true);
    if (!profile.isPresent()) {
        throw new UnauthorizedServiceException("OAuth user profile cannot be determined");
    }
    final UserProfile uProfile = profile.get();
    LOGGER.debug("Creating matching service request based on [{}]", registeredService);
    final boolean requireServiceHeader = oAuthProperties.getGrants().getResourceOwner().isRequireServiceHeader();
    if (requireServiceHeader) {
        LOGGER.debug("Using request headers to identify and build the target service url");
    }
    final Service service = this.authenticationBuilder.buildService(registeredService, context, requireServiceHeader);
    LOGGER.debug("Authenticating the OAuth request indicated by [{}]", service);
    final Authentication authentication = this.authenticationBuilder.build(uProfile, registeredService, context, service);
    final AuditableContext audit = AuditableContext.builder().service(service).authentication(authentication).registeredService(registeredService).retrievePrincipalAttributesFromReleasePolicy(Boolean.TRUE).build();
    final AuditableExecutionResult accessResult = this.registeredServiceAccessStrategyEnforcer.execute(audit);
    accessResult.throwExceptionIfNeeded();
    final AuthenticationResult result = new DefaultAuthenticationResult(authentication, requireServiceHeader ? service : null);
    final TicketGrantingTicket ticketGrantingTicket = this.centralAuthenticationService.createTicketGrantingTicket(result);
    return new AccessTokenRequestDataHolder(service, authentication, registeredService, ticketGrantingTicket, getGrantType(), scopes);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) AuditableContext(org.apereo.cas.audit.AuditableContext) UserProfile(org.pac4j.core.profile.UserProfile) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) Service(org.apereo.cas.authentication.principal.Service) J2EContext(org.pac4j.core.context.J2EContext) DefaultAuthenticationResult(org.apereo.cas.authentication.DefaultAuthenticationResult) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) DefaultAuthenticationResult(org.apereo.cas.authentication.DefaultAuthenticationResult) Authentication(org.apereo.cas.authentication.Authentication) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult)

Example 5 with AuditableExecutionResult

use of org.apereo.cas.audit.AuditableExecutionResult in project cas by apereo.

the class SurrogateEligibilityVerificationAuditResourceResolver method resolveFrom.

@Override
public String[] resolveFrom(final JoinPoint auditableTarget, final Object returnValue) {
    Objects.requireNonNull(returnValue, "AuditableExecutionResult must not be null");
    final AuditableExecutionResult surrogateEligibilityResult = AuditableExecutionResult.class.cast(returnValue);
    final String outcome = "Surrogate Authentication " + BooleanUtils.toString(surrogateEligibilityResult.getProperties().containsKey("eligible"), "Eligible", "Ineligible");
    final ToStringBuilder builder = new ToStringBuilder(this, NO_CLASS_NAME_STYLE).append("result", outcome);
    surrogateEligibilityResult.getService().ifPresent(it -> builder.append("service", it.getId()));
    surrogateEligibilityResult.getAuthentication().ifPresent(it -> builder.append("selfPrincipal", it.getPrincipal()));
    builder.append("surrogatePrincipal", surrogateEligibilityResult.getProperties().get("targetUserId"));
    return new String[] { builder.toString() };
}
Also used : ToStringBuilder(org.apache.commons.lang3.builder.ToStringBuilder) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult)

Aggregations

AuditableExecutionResult (org.apereo.cas.audit.AuditableExecutionResult)19 AuditableContext (org.apereo.cas.audit.AuditableContext)13 RegisteredService (org.apereo.cas.services.RegisteredService)13 Authentication (org.apereo.cas.authentication.Authentication)12 Service (org.apereo.cas.authentication.principal.Service)10 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)7 Audit (org.apereo.inspektr.audit.annotation.Audit)6 Counted (com.codahale.metrics.annotation.Counted)5 Metered (com.codahale.metrics.annotation.Metered)5 Timed (com.codahale.metrics.annotation.Timed)5 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)5 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)4 Principal (org.apereo.cas.authentication.principal.Principal)4 AuditableExecution (org.apereo.cas.audit.AuditableExecution)3 DefaultAuthenticationServiceSelectionPlan (org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionPlan)3 DefaultAuthenticationServiceSelectionStrategy (org.apereo.cas.authentication.DefaultAuthenticationServiceSelectionStrategy)3 ServiceContext (org.apereo.cas.services.ServiceContext)3 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)3 ToStringBuilder (org.apache.commons.lang3.builder.ToStringBuilder)2 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)2