Search in sources :

Example 1 with AuthenticationBuilder

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();
}
Also used : DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) BasicIdentifiableCredential(org.apereo.cas.authentication.BasicIdentifiableCredential) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) HandlerResult(org.apereo.cas.authentication.HandlerResult) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) CredentialMetaData(org.apereo.cas.authentication.CredentialMetaData) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) Principal(org.apereo.cas.authentication.principal.Principal) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData)

Example 2 with AuthenticationBuilder

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);
}
Also used : DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) Credential(org.apereo.cas.authentication.Credential) HttpBasedServiceCredential(org.apereo.cas.authentication.HttpBasedServiceCredential) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) MockTicketGrantingTicket(org.apereo.cas.mock.MockTicketGrantingTicket) DefaultPrincipalFactory(org.apereo.cas.authentication.principal.DefaultPrincipalFactory) MockServiceTicket(org.apereo.cas.mock.MockServiceTicket) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) CachedData(net.spy.memcached.CachedData) NeverExpiresExpirationPolicy(org.apereo.cas.ticket.support.NeverExpiresExpirationPolicy) TicketGrantingTicketImpl(org.apereo.cas.ticket.TicketGrantingTicketImpl) AcceptUsersAuthenticationHandler(org.apereo.cas.authentication.AcceptUsersAuthenticationHandler) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) Test(org.junit.Test)

Example 3 with AuthenticationBuilder

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;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Assertion(org.apereo.cas.validation.Assertion) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) LinkedHashMap(java.util.LinkedHashMap) DefaultAssertionBuilder(org.apereo.cas.validation.DefaultAssertionBuilder) Authentication(org.apereo.cas.authentication.Authentication) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) Principal(org.apereo.cas.authentication.principal.Principal) PostMapping(org.springframework.web.bind.annotation.PostMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 4 with AuthenticationBuilder

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();
}
Also used : DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) DefaultAuthenticationHandlerExecutionResult(org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult) BasicIdentifiableCredential(org.apereo.cas.authentication.BasicIdentifiableCredential) DefaultAuthenticationHandlerExecutionResult(org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult) AuthenticationHandlerExecutionResult(org.apereo.cas.authentication.AuthenticationHandlerExecutionResult) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) CredentialMetaData(org.apereo.cas.authentication.CredentialMetaData) Principal(org.apereo.cas.authentication.principal.Principal) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) HashSet(java.util.HashSet)

Example 5 with AuthenticationBuilder

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;
}
Also used : DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) SimpleTestUsernamePasswordAuthenticationHandler(org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler) SimpleTestUsernamePasswordAuthenticationHandler(org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler) AuthenticationHandler(org.apereo.cas.authentication.AuthenticationHandler) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) CredentialMetaData(org.apereo.cas.authentication.CredentialMetaData) RememberMeUsernamePasswordCredential(org.apereo.cas.authentication.RememberMeUsernamePasswordCredential) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) DefaultAuthenticationHandlerExecutionResult(org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData)

Aggregations

AuthenticationBuilder (org.apereo.cas.authentication.AuthenticationBuilder)6 DefaultAuthenticationBuilder (org.apereo.cas.authentication.DefaultAuthenticationBuilder)5 BasicCredentialMetaData (org.apereo.cas.authentication.BasicCredentialMetaData)4 CredentialMetaData (org.apereo.cas.authentication.CredentialMetaData)3 UsernamePasswordCredential (org.apereo.cas.authentication.UsernamePasswordCredential)3 Principal (org.apereo.cas.authentication.principal.Principal)3 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 Authentication (org.apereo.cas.authentication.Authentication)2 BasicIdentifiableCredential (org.apereo.cas.authentication.BasicIdentifiableCredential)2 DefaultAuthenticationHandlerExecutionResult (org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult)2 DefaultHandlerResult (org.apereo.cas.authentication.DefaultHandlerResult)2 Test (org.junit.Test)2 HashSet (java.util.HashSet)1 CachedData (net.spy.memcached.CachedData)1 AcceptUsersAuthenticationHandler (org.apereo.cas.authentication.AcceptUsersAuthenticationHandler)1 AuthenticationHandler (org.apereo.cas.authentication.AuthenticationHandler)1 AuthenticationHandlerExecutionResult (org.apereo.cas.authentication.AuthenticationHandlerExecutionResult)1 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)1 Credential (org.apereo.cas.authentication.Credential)1