Search in sources :

Example 16 with AuditableExecutionResult

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

the class RegisteredServiceDelegatedAuthenticationPolicyAuditableEnforcer method execute.

@Audit(action = "DELEGATED_CLIENT", actionResolverName = "DELEGATED_CLIENT_ACTION_RESOLVER", resourceResolverName = "DELEGATED_CLIENT_RESOURCE_RESOLVER")
@Override
public AuditableExecutionResult execute(final AuditableContext context) {
    final AuditableExecutionResult result = AuditableExecutionResult.of(context);
    if (context.getRegisteredService().isPresent() && context.getProperties().containsKey(Client.class.getSimpleName())) {
        final RegisteredService registeredService = context.getRegisteredService().get();
        final String clientName = context.getProperties().get(Client.class.getSimpleName()).toString();
        final RegisteredServiceDelegatedAuthenticationPolicy policy = registeredService.getAccessStrategy().getDelegatedAuthenticationPolicy();
        if (policy != null) {
            if (!policy.isProviderAllowed(clientName, registeredService)) {
                LOGGER.debug("Delegated authentication policy for [{}] does not allow for using client [{}]", registeredService, clientName);
                final RuntimeException e = new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, StringUtils.EMPTY);
                result.setException(e);
            }
        }
    }
    return result;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) RegisteredServiceDelegatedAuthenticationPolicy(org.apereo.cas.services.RegisteredServiceDelegatedAuthenticationPolicy) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult) Audit(org.apereo.inspektr.audit.annotation.Audit)

Example 17 with AuditableExecutionResult

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

the class DelegatedClientAuthenticationAction method isDelegatedClientAuthorizedForService.

private boolean isDelegatedClientAuthorizedForService(final Client client, final Service service) {
    if (service == null || StringUtils.isBlank(service.getId())) {
        LOGGER.debug("Can not evaluate delegated authentication policy since no service was provided in the request while processing client [{}]", client);
        return true;
    }
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        LOGGER.warn("Service access for [{}] is denied", registeredService);
        return false;
    }
    LOGGER.debug("Located registered service definition [{}] matching [{}]", registeredService, service);
    final AuditableContext context = AuditableContext.builder().registeredService(registeredService).properties(CollectionUtils.wrap(Client.class.getSimpleName(), client.getName())).build();
    final AuditableExecutionResult result = delegatedAuthenticationPolicyEnforcer.execute(context);
    if (!result.isExecutionFailure()) {
        LOGGER.debug("Delegated authentication policy for [{}] allows for using client [{}]", registeredService, client);
        return true;
    }
    LOGGER.warn("Delegated authentication policy for [{}] refuses access to client [{}]", registeredService.getServiceId(), client);
    return false;
}
Also used : AuditableContext(org.apereo.cas.audit.AuditableContext) RegisteredService(org.apereo.cas.services.RegisteredService) IndirectClient(org.pac4j.core.client.IndirectClient) BaseClient(org.pac4j.core.client.BaseClient) Client(org.pac4j.core.client.Client) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult)

Example 18 with AuditableExecutionResult

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

Example 19 with AuditableExecutionResult

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

the class SurrogateAuthenticationPostProcessor method process.

@Override
public void process(final AuthenticationBuilder builder, final AuthenticationTransaction transaction) throws AuthenticationException {
    final Authentication authentication = builder.build();
    final Principal principal = authentication.getPrincipal();
    final SurrogateUsernamePasswordCredential surrogateCredentials = (SurrogateUsernamePasswordCredential) transaction.getPrimaryCredential().get();
    final String targetUserId = surrogateCredentials.getSurrogateUsername();
    try {
        if (StringUtils.isBlank(targetUserId)) {
            LOGGER.error("No surrogate username was specified as part of the credential");
            throw new CredentialNotFoundException("Missing surrogate username in credential");
        }
        LOGGER.debug("Authenticated [{}] will be checked for surrogate eligibility next...", principal);
        if (transaction.getService() != null) {
            final RegisteredService svc = this.servicesManager.findServiceBy(transaction.getService());
            final AuditableContext serviceAccessAudit = AuditableContext.builder().service(transaction.getService()).authentication(authentication).registeredService(svc).retrievePrincipalAttributesFromReleasePolicy(Boolean.TRUE).build();
            final AuditableExecutionResult accessResult = this.registeredServiceAccessStrategyEnforcer.execute(serviceAccessAudit);
            accessResult.throwExceptionIfNeeded();
        }
        if (this.surrogateAuthenticationService.canAuthenticateAs(targetUserId, principal, transaction.getService())) {
            LOGGER.debug("Principal [{}] is authorized to authenticate as [{}]", principal, targetUserId);
            builder.setPrincipal(this.principalFactory.createPrincipal(targetUserId));
            publishSuccessEvent(principal, targetUserId);
            final AuditableContext surrogateEligibleAudit = AuditableContext.builder().service(transaction.getService()).authentication(authentication).properties(CollectionUtils.wrap("targetUserId", targetUserId, "eligible", true)).build();
            // We don't care about capturing audit execution result here
            this.surrogateEligibilityAuditableExecution.execute(surrogateEligibleAudit);
            return;
        }
        LOGGER.error("Principal [{}] is unable/unauthorized to authenticate as [{}]", principal, targetUserId);
        throw new FailedLoginException();
    } catch (final Exception e) {
        publishFailureEvent(principal, targetUserId);
        final Map<String, Throwable> map = CollectionUtils.wrap(getClass().getSimpleName(), new SurrogateAuthenticationException("Principal " + principal + " is unauthorized to authenticate as " + targetUserId));
        final AuditableContext surrogateIneligibleAudit = AuditableContext.builder().service(transaction.getService()).authentication(authentication).build();
        // We don't care about capturing audit execution result here
        this.surrogateEligibilityAuditableExecution.execute(surrogateIneligibleAudit);
        throw new AuthenticationException(map);
    }
}
Also used : AuditableContext(org.apereo.cas.audit.AuditableContext) RegisteredService(org.apereo.cas.services.RegisteredService) CredentialNotFoundException(javax.security.auth.login.CredentialNotFoundException) CredentialNotFoundException(javax.security.auth.login.CredentialNotFoundException) FailedLoginException(javax.security.auth.login.FailedLoginException) FailedLoginException(javax.security.auth.login.FailedLoginException) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult) Map(java.util.Map) Principal(org.apereo.cas.authentication.principal.Principal)

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