use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class OAuth20AccessTokenControllerTests method internalVerifyClientOK.
private void internalVerifyClientOK(final RegisteredService service, final boolean basicAuth, final boolean refreshToken, final boolean json) throws Exception {
final Principal principal = createPrincipal();
final OAuthCode code = addCode(principal, service);
final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.name().toLowerCase());
if (basicAuth) {
final String auth = CLIENT_ID + ':' + CLIENT_SECRET;
final String value = Base64.encodeBase64String(auth.getBytes(StandardCharsets.UTF_8));
mockRequest.addHeader(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX + value);
} else {
mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
}
mockRequest.setParameter(OAuthConstants.CODE, code.getId());
final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
assertNull(oAuth20AccessTokenController.getTicketRegistry().getTicket(code.getId()));
assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
final String body = mockResponse.getContentAsString();
final String accessTokenId;
if (json) {
assertEquals(MediaType.APPLICATION_JSON_VALUE, mockResponse.getContentType());
assertTrue(body.contains('"' + OAuthConstants.ACCESS_TOKEN + "\":\"AT-"));
if (refreshToken) {
assertTrue(body.contains('"' + OAuthConstants.REFRESH_TOKEN + "\":\"RT-"));
}
assertTrue(body.contains('"' + OAuthConstants.EXPIRES_IN + "\":7"));
accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + "\":\"", "\",\"");
} else {
assertEquals(MediaType.TEXT_PLAIN_VALUE, mockResponse.getContentType());
assertTrue(body.contains(OAuthConstants.ACCESS_TOKEN + "=AT-"));
if (refreshToken) {
assertTrue(body.contains(OAuthConstants.REFRESH_TOKEN + "=RT-"));
}
assertTrue(body.contains(OAuthConstants.EXPIRES_IN + '='));
accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + '=', "&");
}
final AccessToken accessToken = oAuth20AccessTokenController.getTicketRegistry().getTicket(accessTokenId, AccessToken.class);
assertEquals(principal, accessToken.getAuthentication().getPrincipal());
final int timeLeft = getTimeLeft(body, refreshToken, json);
assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class PersonDirectoryAttributeResolutionController method resolvePrincipalAttributes.
/**
* Resolve principal attributes map.
*
* @param uid the uid
* @param request the request
* @param response the response
* @return the map
*/
@PostMapping(value = "/resolveattrs")
@ResponseBody
public Map<String, Object> resolvePrincipalAttributes(@RequestParam final String uid, final HttpServletRequest request, final HttpServletResponse response) {
ensureEndpointAccessIsAuthorized(request, response);
final Principal p = personDirectoryPrincipalResolver.resolve(new BasicIdentifiableCredential(uid));
final Map<String, Object> map = new LinkedHashMap<>();
map.put("uid", p.getId());
map.put("attributes", p.getAttributes());
return map;
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class PersonDirectoryAttributeResolutionController method releasePrincipalAttributes.
/**
* Release principal attributes map.
*
* @param username the username
* @param password the password
* @param service the service
* @param request the request
* @param response the response
* @return the map
* @throws Exception the exception
*/
@PostMapping(value = "/releaseattrs")
@ResponseBody
public Map<String, Object> releasePrincipalAttributes(@RequestParam final String username, @RequestParam final String password, @RequestParam final String service, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
ensureEndpointAccessIsAuthorized(request, response);
final Map<String, Object> resValidation = new HashMap<>();
final Service selectedService = this.serviceFactory.createService(service);
final RegisteredService registeredService = this.servicesManager.findServiceBy(selectedService);
final UsernamePasswordCredential credential = new UsernamePasswordCredential(username, password);
final AuthenticationResult result = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(selectedService, credential);
final Authentication authentication = result.getAuthentication();
final Principal principal = authentication.getPrincipal();
final Map<String, Object> attributesToRelease = registeredService.getAttributeReleasePolicy().getAttributes(principal, selectedService, registeredService);
final String principalId = registeredService.getUsernameAttributeProvider().resolveUsername(principal, selectedService, registeredService);
final Principal modifiedPrincipal = this.principalFactory.createPrincipal(principalId, attributesToRelease);
final AuthenticationBuilder builder = DefaultAuthenticationBuilder.newInstance(authentication);
builder.setPrincipal(modifiedPrincipal);
final Authentication finalAuthentication = builder.build();
final Assertion assertion = new DefaultAssertionBuilder(finalAuthentication).with(selectedService).with(CollectionUtils.wrap(finalAuthentication)).build();
final Map<String, Object> model = new LinkedHashMap<>();
model.put(CasViewConstants.MODEL_ATTRIBUTE_NAME_ASSERTION, assertion);
model.put(CasViewConstants.MODEL_ATTRIBUTE_NAME_SERVICE, selectedService);
resValidation.put("registeredService", registeredService);
String copy = renderViewAndGetResult(this.cas1ServiceSuccessView, model, request, response).getKey().getCopy();
resValidation.put("cas1Response", StringEscapeUtils.escapeXml11(copy));
if (casProperties.getView().getCas2().isV3ForwardCompatible()) {
copy = renderViewAndGetResult(this.cas3ServiceSuccessView, model, request, response).getKey().getCopy();
} else {
copy = renderViewAndGetResult(this.cas2ServiceSuccessView, model, request, response).getKey().getCopy();
}
resValidation.put("cas2Response", StringEscapeUtils.escapeXml11(copy));
copy = renderViewAndGetResult(this.cas3ServiceSuccessView, model, request, response).getKey().getCopy();
resValidation.put("cas3XmlResponse", StringEscapeUtils.escapeXml11(copy));
copy = renderViewAndGetResult(this.cas3ServiceJsonView, model, request, response).getValue().getStringCopy();
resValidation.put("cas3JsonResponse", copy);
response.reset();
return resValidation;
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class SingleSignOnSessionsReportController method getActiveSsoSessions.
/**
* Gets sso sessions.
*
* @param option the option
* @return the sso sessions
*/
private Collection<Map<String, Object>> getActiveSsoSessions(final SsoSessionReportOptions option) {
final Collection<Map<String, Object>> activeSessions = new ArrayList<>();
final ISOStandardDateFormat dateFormat = new ISOStandardDateFormat();
getNonExpiredTicketGrantingTickets().stream().map(TicketGrantingTicket.class::cast).filter(tgt -> !(option == SsoSessionReportOptions.DIRECT && tgt.getProxiedBy() != null)).forEach(tgt -> {
final Authentication authentication = tgt.getAuthentication();
final Principal principal = authentication.getPrincipal();
final Map<String, Object> sso = new HashMap<>(SsoSessionAttributeKeys.values().length);
sso.put(SsoSessionAttributeKeys.AUTHENTICATED_PRINCIPAL.getAttributeKey(), principal.getId());
sso.put(SsoSessionAttributeKeys.AUTHENTICATION_DATE.getAttributeKey(), authentication.getAuthenticationDate());
sso.put(SsoSessionAttributeKeys.AUTHENTICATION_DATE_FORMATTED.getAttributeKey(), dateFormat.format(DateTimeUtils.dateOf(authentication.getAuthenticationDate())));
sso.put(SsoSessionAttributeKeys.NUMBER_OF_USES.getAttributeKey(), tgt.getCountOfUses());
sso.put(SsoSessionAttributeKeys.TICKET_GRANTING_TICKET.getAttributeKey(), tgt.getId());
sso.put(SsoSessionAttributeKeys.PRINCIPAL_ATTRIBUTES.getAttributeKey(), principal.getAttributes());
sso.put(SsoSessionAttributeKeys.AUTHENTICATION_ATTRIBUTES.getAttributeKey(), authentication.getAttributes());
if (option != SsoSessionReportOptions.DIRECT) {
if (tgt.getProxiedBy() != null) {
sso.put(SsoSessionAttributeKeys.IS_PROXIED.getAttributeKey(), Boolean.TRUE);
sso.put(SsoSessionAttributeKeys.PROXIED_BY.getAttributeKey(), tgt.getProxiedBy().getId());
} else {
sso.put(SsoSessionAttributeKeys.IS_PROXIED.getAttributeKey(), Boolean.FALSE);
}
}
sso.put(SsoSessionAttributeKeys.AUTHENTICATED_SERVICES.getAttributeKey(), tgt.getServices());
activeSessions.add(sso);
});
return activeSessions;
}
use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.
the class DefaultAuthenticationResultBuilder method buildAuthenticationHistory.
private static void buildAuthenticationHistory(final Set<Authentication> authentications, final Map<String, Object> authenticationAttributes, final Map<String, Object> principalAttributes, final AuthenticationBuilder authenticationBuilder) {
LOGGER.debug("Collecting authentication history based on [{}] authentication events", authentications.size());
authentications.stream().forEach(authn -> {
final Principal authenticatedPrincipal = authn.getPrincipal();
LOGGER.debug("Evaluating authentication principal [{}] for inclusion in result", authenticatedPrincipal);
principalAttributes.putAll(authenticatedPrincipal.getAttributes());
LOGGER.debug("Collected principal attributes [{}] for inclusion in this result for principal [{}]", principalAttributes, authenticatedPrincipal.getId());
authn.getAttributes().keySet().stream().forEach(attrName -> {
if (authenticationAttributes.containsKey(attrName)) {
LOGGER.debug("Collecting multi-valued authentication attribute [{}]", attrName);
final Object oldValue = authenticationAttributes.remove(attrName);
LOGGER.debug("Converting authentication attribute [{}] to a collection of values", attrName);
final Collection<Object> listOfValues = CollectionUtils.toCollection(oldValue);
final Object newValue = authn.getAttributes().get(attrName);
listOfValues.addAll(CollectionUtils.toCollection(newValue));
authenticationAttributes.put(attrName, listOfValues);
LOGGER.debug("Collected multi-valued authentication attribute [{}] -> [{}]", attrName, listOfValues);
} else {
final Object value = authn.getAttributes().get(attrName);
if (value != null) {
authenticationAttributes.put(attrName, value);
LOGGER.debug("Collected single authentication attribute [{}] -> [{}]", attrName, value);
} else {
LOGGER.warn("Authentication attribute [{}] has no value and is not collected", attrName);
}
}
});
LOGGER.debug("Finalized authentication attributes [{}] for inclusion in this authentication result", authenticationAttributes);
authenticationBuilder.addSuccesses(authn.getSuccesses()).addFailures(authn.getFailures()).addCredentials(authn.getCredentials());
});
}
Aggregations