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();
}
}
}
}
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));
}
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;
}
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);
}
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() };
}
Aggregations