use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class GrouperMultifactorAuthenticationPolicyEventResolver method resolveInternal.
@Override
public Set<Event> resolveInternal(final RequestContext context) {
final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
final Authentication authentication = WebUtils.getAuthentication(context);
if (StringUtils.isBlank(grouperField)) {
LOGGER.debug("No group field is defined to process for Grouper multifactor trigger");
return null;
}
if (authentication == null || service == null) {
LOGGER.debug("No authentication or service is available to determine event for principal");
return null;
}
final Principal principal = authentication.getPrincipal();
final Collection<WsGetGroupsResult> results = GrouperFacade.getGroupsForSubjectId(principal.getId());
if (results.isEmpty()) {
LOGGER.debug("No groups could be found for [{}] to resolve events for MFA", principal);
return null;
}
final Map<String, MultifactorAuthenticationProvider> providerMap = MultifactorAuthenticationUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext);
if (providerMap == null || providerMap.isEmpty()) {
LOGGER.error("No multifactor authentication providers are available in the application context");
throw new AuthenticationException();
}
final GrouperGroupField groupField = GrouperGroupField.valueOf(grouperField);
final Set<String> values = results.stream().map(wsGetGroupsResult -> Stream.of(wsGetGroupsResult.getWsGroups())).flatMap(Function.identity()).map(g -> GrouperFacade.getGrouperGroupAttribute(groupField, g)).collect(Collectors.toSet());
final Optional<MultifactorAuthenticationProvider> providerFound = resolveProvider(providerMap, values);
if (providerFound.isPresent()) {
final MultifactorAuthenticationProvider provider = providerFound.get();
if (provider.isAvailable(service)) {
LOGGER.debug("Attempting to build event based on the authentication provider [{}] and service [{}]", provider, service.getName());
final Event event = validateEventIdForMatchingTransitionInContext(provider.getId(), context, buildEventAttributeMap(authentication.getPrincipal(), service, provider));
return CollectionUtils.wrapSet(event);
}
LOGGER.warn("Located multifactor provider [{}], yet the provider cannot be reached or verified", providerFound.get());
return null;
}
LOGGER.debug("No multifactor provider could be found based on [{}]'s Grouper groups", principal.getId());
return null;
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class Saml2AttributeQueryProfileHandlerController method handlePostRequest.
/**
* Handle post request.
*
* @param response the response
* @param request the request
*/
@PostMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SOAP_ATTRIBUTE_QUERY)
protected void handlePostRequest(final HttpServletResponse response, final HttpServletRequest request) {
final MessageContext ctx = decodeSoapRequest(request);
final AttributeQuery query = (AttributeQuery) ctx.getMessage();
try {
final String issuer = query.getIssuer().getValue();
final SamlRegisteredService service = verifySamlRegisteredService(issuer);
final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> adaptor = getSamlMetadataFacadeFor(service, query);
if (!adaptor.isPresent()) {
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
}
final SamlRegisteredServiceServiceProviderMetadataFacade facade = adaptor.get();
verifyAuthenticationContextSignature(ctx, request, query, facade);
final Map<String, Object> attrs = new LinkedHashMap<>();
if (query.getAttributes().isEmpty()) {
final String id = this.samlAttributeQueryTicketFactory.createTicketIdFor(query.getSubject().getNameID().getValue());
final SamlAttributeQueryTicket ticket = this.ticketRegistry.getTicket(id, SamlAttributeQueryTicket.class);
final Authentication authentication = ticket.getTicketGrantingTicket().getAuthentication();
final Principal principal = authentication.getPrincipal();
final Map<String, Object> authnAttrs = authentication.getAttributes();
final Map<String, Object> principalAttrs = principal.getAttributes();
query.getAttributes().forEach(a -> {
if (authnAttrs.containsKey(a.getName())) {
attrs.put(a.getName(), authnAttrs.get(a.getName()));
} else if (principalAttrs.containsKey(a.getName())) {
attrs.put(a.getName(), principalAttrs.get(a.getName()));
}
});
}
final Assertion casAssertion = buildCasAssertion(issuer, service, attrs);
this.responseBuilder.build(query, request, response, casAssertion, service, facade, SAMLConstants.SAML2_SOAP11_BINDING_URI);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
request.setAttribute(SamlIdPConstants.REQUEST_ATTRIBUTE_ERROR, e.getMessage());
samlFaultResponseBuilder.build(query, request, response, null, null, null, SAMLConstants.SAML2_SOAP11_BINDING_URI);
}
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class OAuth20CasAuthenticationBuilder method build.
/**
* Create an authentication from a user profile.
*
* @param profile the given user profile
* @param registeredService the registered service
* @param context the context
* @param service the service
* @return the built authentication
*/
public Authentication build(final UserProfile profile, final OAuthRegisteredService registeredService, final J2EContext context, final Service service) {
final Map<String, Object> profileAttributes = getPrincipalAttributesFromProfile(profile);
final Principal newPrincipal = this.principalFactory.createPrincipal(profile.getId(), profileAttributes);
LOGGER.debug("Created final principal [{}] after filtering attributes based on [{}]", newPrincipal, registeredService);
final String authenticator = profile.getClass().getCanonicalName();
final CredentialMetaData metadata = new BasicCredentialMetaData(new BasicIdentifiableCredential(profile.getId()));
final AuthenticationHandlerExecutionResult handlerResult = new DefaultAuthenticationHandlerExecutionResult(authenticator, metadata, newPrincipal, new ArrayList<>());
final Set<Object> scopes = CollectionUtils.toCollection(context.getRequest().getParameterValues(OAuth20Constants.SCOPE));
final String state = StringUtils.defaultIfBlank(context.getRequestParameter(OAuth20Constants.STATE), StringUtils.EMPTY);
final String nonce = StringUtils.defaultIfBlank(context.getRequestParameter(OAuth20Constants.NONCE), StringUtils.EMPTY);
LOGGER.debug("OAuth [{}] is [{}], and [{}] is [{}]", OAuth20Constants.STATE, state, OAuth20Constants.NONCE, nonce);
/*
* pac4j UserProfile.getPermissions() and getRoles() returns UnmodifiableSet which Jackson Serializer
* happily serializes to json but is unable to deserialize.
* We have to of it to HashSet to avoid such problem
*/
final AuthenticationBuilder bldr = DefaultAuthenticationBuilder.newInstance().addAttribute("permissions", new HashSet<>(profile.getPermissions())).addAttribute("roles", new HashSet<>(profile.getRoles())).addAttribute("scopes", scopes).addAttribute(OAuth20Constants.STATE, state).addAttribute(OAuth20Constants.NONCE, nonce).addCredential(metadata).setPrincipal(newPrincipal).setAuthenticationDate(ZonedDateTime.now()).addSuccess(profile.getClass().getCanonicalName(), handlerResult);
collectionAuthenticationAttributesIfNecessary(profile, bldr);
return bldr.build();
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class DefaultOAuth2UserProfileDataCreator method getAccessTokenAuthenticationPrincipal.
/**
* Gets access token authentication principal.
*
* @param accessToken the access token
* @param context the context
* @return the access token authentication principal
*/
protected Principal getAccessTokenAuthenticationPrincipal(final AccessToken accessToken, final J2EContext context) {
final Service service = accessToken.getService();
final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
final Principal currentPrincipal = accessToken.getAuthentication().getPrincipal();
LOGGER.debug("Preparing user profile response based on CAS principal [{}]", currentPrincipal);
final Principal principal = this.scopeToAttributesFilter.filter(accessToken.getService(), currentPrincipal, registeredService, context, accessToken);
LOGGER.debug("Created CAS principal [{}] based on requested/authorized scopes", principal);
return principal;
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class AbstractOAuth20Tests method internalVerifyClientOK.
protected Pair<String, String> internalVerifyClientOK(final RegisteredService service, final boolean refreshToken, final boolean json) throws Exception {
final Principal principal = createPrincipal();
final OAuthCode code = addCode(principal, service);
final MockHttpServletRequest mockRequest = new MockHttpServletRequest(HttpMethod.GET.name(), CONTEXT + OAuth20Constants.ACCESS_TOKEN_URL);
mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI);
mockRequest.setParameter(OAuth20Constants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.name().toLowerCase());
final String auth = CLIENT_ID + ':' + CLIENT_SECRET;
final String value = EncodingUtils.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
mockRequest.addHeader(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX + value);
mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
mockRequest.setParameter(OAuth20Constants.CLIENT_SECRET, CLIENT_SECRET);
mockRequest.setParameter(OAuth20Constants.CODE, code.getId());
final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
oAuth20AccessTokenController.handleRequest(mockRequest, mockResponse);
assertNull(this.ticketRegistry.getTicket(code.getId()));
assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
final String body = mockResponse.getContentAsString();
final String accessTokenId;
String refreshTokenId = null;
if (json) {
assertEquals(MediaType.APPLICATION_JSON_VALUE, mockResponse.getContentType());
assertTrue(body.contains('"' + OAuth20Constants.ACCESS_TOKEN + "\":\"AT-"));
final Map results = MAPPER.readValue(body, Map.class);
if (refreshToken) {
assertTrue(body.contains('"' + OAuth20Constants.REFRESH_TOKEN + "\":\"RT-"));
refreshTokenId = results.get(OAuth20Constants.REFRESH_TOKEN).toString();
}
assertTrue(body.contains('"' + OAuth20Constants.EXPIRES_IN + "\":"));
accessTokenId = results.get(OAuth20Constants.ACCESS_TOKEN).toString();
} else {
assertEquals(MediaType.TEXT_PLAIN_VALUE, mockResponse.getContentType());
assertTrue(body.contains(OAuth20Constants.ACCESS_TOKEN + "=AT-"));
if (refreshToken) {
assertTrue(body.contains(OAuth20Constants.REFRESH_TOKEN + "=RT-"));
refreshTokenId = Arrays.stream(body.split("&")).filter(f -> f.startsWith(OAuth20Constants.REFRESH_TOKEN)).map(f -> StringUtils.remove(f, OAuth20Constants.REFRESH_TOKEN + "=")).findFirst().get();
}
assertTrue(body.contains(OAuth20Constants.EXPIRES_IN + '='));
accessTokenId = StringUtils.substringBetween(body, OAuth20Constants.ACCESS_TOKEN + '=', "&");
}
final AccessToken accessToken = this.ticketRegistry.getTicket(accessTokenId, AccessToken.class);
assertEquals(principal, accessToken.getAuthentication().getPrincipal());
final int timeLeft = getTimeLeft(body, refreshToken, json);
assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
return Pair.of(accessTokenId, refreshTokenId);
}
Aggregations