use of org.apereo.cas.authentication.AuthenticationBuilder in project cas by apereo.
the class BaseOAuthWrapperController method createAuthentication.
/**
* 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
*/
protected Authentication createAuthentication(final UserProfile profile, final RegisteredService registeredService, final J2EContext context, final Service service) {
final Principal newPrincipal = this.scopeToAttributesFilter.filter(service, this.principalFactory.createPrincipal(profile.getId(), profile.getAttributes()), registeredService, context);
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 HandlerResult handlerResult = new DefaultHandlerResult(authenticator, metadata, newPrincipal, new ArrayList<>());
final String state = StringUtils.defaultIfBlank(context.getRequestParameter(OAuthConstants.STATE), StringUtils.EMPTY);
final String nonce = StringUtils.defaultIfBlank(context.getRequestParameter(OAuthConstants.NONCE), StringUtils.EMPTY);
LOGGER.debug("OAuth [{}] is [{}], and [{}] is [{}]", OAuthConstants.STATE, state, OAuthConstants.NONCE, nonce);
final AuthenticationBuilder bldr = DefaultAuthenticationBuilder.newInstance().addAttribute("permissions", profile.getPermissions()).addAttribute("roles", profile.getRoles()).addAttribute(OAuthConstants.STATE, state).addAttribute(OAuthConstants.NONCE, nonce).addCredential(metadata).setPrincipal(newPrincipal).setAuthenticationDate(ZonedDateTime.now()).addSuccess(profile.getClass().getCanonicalName(), handlerResult);
// Add "other" profile attributes as authentication attributes.
if (casProperties.getAuthn().getOauth().getAccessToken().isReleaseProtocolAttributes()) {
profile.getAttributes().forEach((k, v) -> {
if (!newPrincipal.getAttributes().containsKey(k)) {
LOGGER.debug("Added attribute [{}] with value [{}] to the authentication", k, v);
bldr.addAttribute(k, v);
} else {
LOGGER.debug("Skipped over attribute [{}] since it's already contained by the principal", k);
}
});
}
return bldr.build();
}
use of org.apereo.cas.authentication.AuthenticationBuilder in project cas by apereo.
the class KryoTranscoderTests method verifyEncodeDecodeTGTImpl.
@Test
public void verifyEncodeDecodeTGTImpl() throws Exception {
final Credential userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
final AuthenticationBuilder bldr = new DefaultAuthenticationBuilder(new DefaultPrincipalFactory().createPrincipal("user", new HashMap<>(this.principalAttributes)));
bldr.setAttributes(new HashMap<>(this.principalAttributes));
bldr.setAuthenticationDate(ZonedDateTime.now());
bldr.addCredential(new BasicCredentialMetaData(userPassCredential));
bldr.addFailure("error", AccountNotFoundException.class);
bldr.addSuccess("authn", new DefaultHandlerResult(new AcceptUsersAuthenticationHandler(""), new BasicCredentialMetaData(userPassCredential)));
final TicketGrantingTicket expectedTGT = new TicketGrantingTicketImpl(TGT_ID, RegisteredServiceTestUtils.getService(), null, bldr.build(), new NeverExpiresExpirationPolicy());
final ServiceTicket ticket = expectedTGT.grantServiceTicket(ST_ID, RegisteredServiceTestUtils.getService(), new NeverExpiresExpirationPolicy(), false, true);
CachedData result = transcoder.encode(expectedTGT);
final TicketGrantingTicket resultTicket = (TicketGrantingTicket) transcoder.decode(result);
assertEquals(expectedTGT, resultTicket);
result = transcoder.encode(ticket);
final ServiceTicket resultStTicket = (ServiceTicket) transcoder.decode(result);
assertEquals(ticket, resultStTicket);
}
use of org.apereo.cas.authentication.AuthenticationBuilder 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.AuthenticationBuilder 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.AuthenticationBuilder in project cas by apereo.
the class RememberMeAuthenticationMetaDataPopulatorTests method newBuilder.
private AuthenticationBuilder newBuilder(final Credential credential) {
final CredentialMetaData meta = new BasicCredentialMetaData(new UsernamePasswordCredential());
final AuthenticationHandler handler = new SimpleTestUsernamePasswordAuthenticationHandler();
final AuthenticationBuilder builder = new DefaultAuthenticationBuilder(CoreAuthenticationTestUtils.getPrincipal()).addCredential(meta).addSuccess("test", new DefaultAuthenticationHandlerExecutionResult(handler, meta));
if (this.p.supports(credential)) {
this.p.populateAttributes(builder, AuthenticationTransaction.of(credential));
}
return builder;
}
Aggregations