Java Code Examples for org.jasig.cas.authentication.Authentication#getPrincipal()

The following examples show how to use org.jasig.cas.authentication.Authentication#getPrincipal() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CentralAuthenticationServiceImpl.java    From taoshop with Apache License 2.0 6 votes vote down vote up
/**
 * Always keep track of a single authentication object,
 * as opposed to keeping a history of all. This helps with
 * memory consumption. Note that supplemental authentications
 * are to be removed.
 *
 * @param context              authentication context
 * @param ticketGrantingTicket the tgt
 * @return the processed authentication in the current context
 * @throws MixedPrincipalException in case there is a principal mismatch between TGT and the current authN.
 */
private Authentication evaluatePossibilityOfMixedPrincipals(final AuthenticationContext context,
                                                                   final TicketGrantingTicket ticketGrantingTicket)
        throws MixedPrincipalException {
    Authentication currentAuthentication = null;
    if (context != null) {
        currentAuthentication = context.getAuthentication();
        if (currentAuthentication != null) {
            final Authentication original = ticketGrantingTicket.getAuthentication();
            if (!currentAuthentication.getPrincipal().equals(original.getPrincipal())) {
                logger.debug("Principal associated with current authentication {} does not match "
                        + " the principal {} associated with the original authentication",
                        currentAuthentication.getPrincipal(), original.getPrincipal());
                throw new MixedPrincipalException(
                        currentAuthentication, currentAuthentication.getPrincipal(), original.getPrincipal());
            }
            ticketGrantingTicket.getSupplementalAuthentications().clear();
            ticketGrantingTicket.getSupplementalAuthentications().add(currentAuthentication);
            logger.debug("Added authentication to the collection of supplemental authentications");
        }
    }
    return currentAuthentication;
}
 
Example 2
Source File: MultiFactorCredentials.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
/**
 * Enumerates the list of available principals in the authentication chain
 * and ensures that the newly given and provided principal is compliant
 * and equals the rest of the principals in the chain. The match
 * is explicitly controlled by {@link Principal#equals(Object)}
 * implementation.
 *
 * @param authentication the authentication object whose principal is compared against the chain
 * @return true if no mismatch is found; false otherwise.
 */
private boolean doesPrincipalMatchAuthenticationChain(final Authentication authentication) {
    for (final Authentication authn : this.chainedAuthentication) {
        final Principal currentPrincipal = authn.getPrincipal();
        final Principal newPrincipal = authentication.getPrincipal();

        if (!currentPrincipal.equals(newPrincipal)) {
            return false;
        }
    }
    return true;
}
 
Example 3
Source File: MultiFactorCredentials.java    From cas-mfa with Apache License 2.0 5 votes vote down vote up
/**
 * Provides the ability to access the resolved
 * and primary principal based on the authentication context.
 * @return the primary principal.
 */
public final Principal getPrincipal() {
    final Authentication auth = this.getAuthentication();
    if (auth != null) {
        return auth.getPrincipal();
    }
    return null;
}
 
Example 4
Source File: CentralAuthenticationServiceImpl.java    From taoshop with Apache License 2.0 4 votes vote down vote up
@Audit(
        action = "SERVICE_TICKET_VALIDATE",
        actionResolverName = "VALIDATE_SERVICE_TICKET_RESOLVER",
        resourceResolverName = "VALIDATE_SERVICE_TICKET_RESOURCE_RESOLVER")
@Timed(name = "VALIDATE_SERVICE_TICKET_TIMER")
@Metered(name = "VALIDATE_SERVICE_TICKET_METER")
@Counted(name = "VALIDATE_SERVICE_TICKET_COUNTER", monotonic = true)
@Override
public Assertion validateServiceTicket(final String serviceTicketId, final Service service) throws AbstractTicketException {
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    verifyRegisteredServiceProperties(registeredService, service);

    final ServiceTicket serviceTicket = this.ticketRegistry.getTicket(serviceTicketId, ServiceTicket.class);

    if (serviceTicket == null) {
        logger.info("Service ticket [{}] does not exist.", serviceTicketId);
        throw new InvalidTicketException(serviceTicketId);
    }

    try {
        synchronized (serviceTicket) {
            if (serviceTicket.isExpired()) {
                logger.info("ServiceTicket [{}] has expired.", serviceTicketId);
                throw new InvalidTicketException(serviceTicketId);
            }

            if (!serviceTicket.isValidFor(service)) {
                logger.error("Service ticket [{}] with service [{}] does not match supplied service [{}]",
                        serviceTicketId, serviceTicket.getService().getId(), service);
                throw new UnrecognizableServiceForServiceTicketValidationException(serviceTicket.getService());
            }
        }

        final TicketGrantingTicket root = serviceTicket.getGrantingTicket().getRoot();
        final Authentication authentication = getAuthenticationSatisfiedByPolicy(
                root, new ServiceContext(serviceTicket.getService(), registeredService));
        final Principal principal = authentication.getPrincipal();

        final RegisteredServiceAttributeReleasePolicy attributePolicy = registeredService.getAttributeReleasePolicy();
        logger.debug("Attribute policy [{}] is associated with service [{}]", attributePolicy, registeredService);

        @SuppressWarnings("unchecked")
        final Map<String, Object> attributesToRelease = attributePolicy != null
                ? attributePolicy.getAttributes(principal) : Collections.EMPTY_MAP;

        final String principalId = registeredService.getUsernameAttributeProvider().resolveUsername(principal, service);
        final Principal modifiedPrincipal = this.principalFactory.createPrincipal(principalId, attributesToRelease);
        final AuthenticationBuilder builder = DefaultAuthenticationBuilder.newInstance(authentication);
        builder.setPrincipal(modifiedPrincipal);

        final Assertion assertion = new ImmutableAssertion(
                builder.build(),
                serviceTicket.getGrantingTicket().getChainedAuthentications(),
                serviceTicket.getService(),
                serviceTicket.isFromNewLogin());

        doPublishEvent(new CasServiceTicketValidatedEvent(this, serviceTicket, assertion));

        return assertion;

    } finally {
        if (serviceTicket.isExpired()) {
            this.ticketRegistry.deleteTicket(serviceTicketId);
        }
    }
}
 
Example 5
Source File: CentralAuthenticationServiceImpl.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
@Audit(
    action="SERVICE_TICKET",
    actionResolverName="GRANT_SERVICE_TICKET_RESOLVER",
    resourceResolverName="GRANT_SERVICE_TICKET_RESOURCE_RESOLVER")
@Timed(name="GRANT_SERVICE_TICKET_TIMER")
@Metered(name="GRANT_SERVICE_TICKET_METER")
@Counted(name="GRANT_SERVICE_TICKET_COUNTER", monotonic=true)
@Override
public ServiceTicket grantServiceTicket(
        final String ticketGrantingTicketId,
        final Service service, final Credential... credentials)
        throws AuthenticationException, TicketException {

    final TicketGrantingTicket ticketGrantingTicket = getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    verifyRegisteredServiceProperties(registeredService, service);
    final Set<Credential> sanitizedCredentials = sanitizeCredentials(credentials);

    Authentication currentAuthentication = null;
    if (sanitizedCredentials.size() > 0) {
        currentAuthentication = this.authenticationManager.authenticate(
                sanitizedCredentials.toArray(new Credential[] {}));
        final Authentication original = ticketGrantingTicket.getAuthentication();
        if (!currentAuthentication.getPrincipal().equals(original.getPrincipal())) {
            throw new MixedPrincipalException(
                    currentAuthentication, currentAuthentication.getPrincipal(), original.getPrincipal());
        }
        ticketGrantingTicket.getSupplementalAuthentications().add(currentAuthentication);
    }

    if (currentAuthentication == null && !registeredService.getAccessStrategy().isServiceAccessAllowedForSso()) {
        logger.warn("ServiceManagement: Service [{}] is not allowed to use SSO.", service.getId());
        throw new UnauthorizedSsoServiceException();
    }

    final Service proxiedBy = ticketGrantingTicket.getProxiedBy();
    if (proxiedBy != null) {
        logger.debug("TGT is proxied by [{}]. Locating proxy service in registry...", proxiedBy.getId());
        final RegisteredService proxyingService = servicesManager.findServiceBy(proxiedBy);

        if (proxyingService != null) {
            logger.debug("Located proxying service [{}] in the service registry", proxyingService);
            if (!proxyingService.getProxyPolicy().isAllowedToProxy()) {
                logger.warn("Found proxying service {}, but it is not authorized to fulfill the proxy attempt made by {}",
                        proxyingService.getId(), service.getId());
                throw new UnauthorizedProxyingException("Proxying is not allowed for registered service "
                        + registeredService.getId());
            }
        } else {
            logger.warn("No proxying service found. Proxy attempt by service [{}] (registered service [{}]) is not allowed.",
                    service.getId(), registeredService.getId());
            throw new UnauthorizedProxyingException("Proxying is not allowed for registered service "
                    + registeredService.getId());
        }
    } else {
        logger.trace("TGT is not proxied by another service");
    }

    // Perform security policy check by getting the authentication that satisfies the configured policy
    // This throws if no suitable policy is found
    getAuthenticationSatisfiedByPolicy(ticketGrantingTicket, new ServiceContext(service, registeredService));

    final List<Authentication> authentications = ticketGrantingTicket.getChainedAuthentications();
    final Principal principal = authentications.get(authentications.size() - 1).getPrincipal();

    final Map<String, Object> principalAttrs = registeredService.getAttributeReleasePolicy().getAttributes(principal);
    if (!registeredService.getAccessStrategy().doPrincipalAttributesAllowServiceAccess(principalAttrs)) {
        logger.warn("ServiceManagement: Cannot grant service ticket because Service [{}] is not authorized for use by [{}].",
                service.getId(), principal);
        throw new UnauthorizedServiceForPrincipalException();
    }

    final String uniqueTicketIdGenKey = service.getClass().getName();
    logger.debug("Looking up service ticket id generator for [{}]", uniqueTicketIdGenKey);
    UniqueTicketIdGenerator serviceTicketUniqueTicketIdGenerator =
            this.uniqueTicketIdGeneratorsForService.get(uniqueTicketIdGenKey);
    if (serviceTicketUniqueTicketIdGenerator == null) {
        serviceTicketUniqueTicketIdGenerator = this.defaultServiceTicketIdGenerator;
        logger.debug("Service ticket id generator not found for [{}]. Using the default generator...",
                uniqueTicketIdGenKey);
    }

    final String ticketPrefix = authentications.size() == 1 ? ServiceTicket.PREFIX : ServiceTicket.PROXY_TICKET_PREFIX;
    final String ticketId = serviceTicketUniqueTicketIdGenerator.getNewTicketId(ticketPrefix);
    final ServiceTicket serviceTicket = ticketGrantingTicket.grantServiceTicket(
            ticketId,
            service,
            this.serviceTicketExpirationPolicy,
            currentAuthentication != null);

    this.serviceTicketRegistry.addTicket(serviceTicket);

    logger.info("Granted ticket [{}] for service [{}] for user [{}]",
            serviceTicket.getId(), service.getId(), principal.getId());

    return serviceTicket;
}
 
Example 6
Source File: CentralAuthenticationServiceImpl.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
@Audit(
    action="SERVICE_TICKET_VALIDATE",
    actionResolverName="VALIDATE_SERVICE_TICKET_RESOLVER",
    resourceResolverName="VALIDATE_SERVICE_TICKET_RESOURCE_RESOLVER")
@Timed(name="VALIDATE_SERVICE_TICKET_TIMER")
@Metered(name="VALIDATE_SERVICE_TICKET_METER")
@Counted(name="VALIDATE_SERVICE_TICKET_COUNTER", monotonic=true)
@Override
public Assertion validateServiceTicket(final String serviceTicketId, final Service service) throws TicketException {
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    verifyRegisteredServiceProperties(registeredService, service);

    final ServiceTicket serviceTicket =  this.serviceTicketRegistry.getTicket(serviceTicketId, ServiceTicket.class);

    if (serviceTicket == null) {
        logger.info("Service ticket [{}] does not exist.", serviceTicketId);
        throw new InvalidTicketException(serviceTicketId);
    }

    try {
        synchronized (serviceTicket) {
            if (serviceTicket.isExpired()) {
                logger.info("ServiceTicket [{}] has expired.", serviceTicketId);
                throw new InvalidTicketException(serviceTicketId);
            }

            if (!serviceTicket.isValidFor(service)) {
                logger.error("Service ticket [{}] with service [{}] does not match supplied service [{}]",
                        serviceTicketId, serviceTicket.getService().getId(), service);
                throw new UnrecognizableServiceForServiceTicketValidationException(serviceTicket.getService());
            }
        }

        final TicketGrantingTicket root = serviceTicket.getGrantingTicket().getRoot();
        final Authentication authentication = getAuthenticationSatisfiedByPolicy(
                root, new ServiceContext(serviceTicket.getService(), registeredService));
        final Principal principal = authentication.getPrincipal();

        final AttributeReleasePolicy attributePolicy = registeredService.getAttributeReleasePolicy();
        logger.debug("Attribute policy [{}] is associated with service [{}]", attributePolicy, registeredService);
        
        @SuppressWarnings("unchecked")
        final Map<String, Object> attributesToRelease = attributePolicy != null
                ? attributePolicy.getAttributes(principal) : Collections.EMPTY_MAP;
        
        final String principalId = registeredService.getUsernameAttributeProvider().resolveUsername(principal, service);
        final Principal modifiedPrincipal = this.principalFactory.createPrincipal(principalId, attributesToRelease);
        final AuthenticationBuilder builder = DefaultAuthenticationBuilder.newInstance(authentication);
        builder.setPrincipal(modifiedPrincipal);

        return new ImmutableAssertion(
                builder.build(),
                serviceTicket.getGrantingTicket().getChainedAuthentications(),
                serviceTicket.getService(),
                serviceTicket.isFromNewLogin());
    } finally {
        if (serviceTicket.isExpired()) {
            this.serviceTicketRegistry.deleteTicket(serviceTicketId);
        }
    }
}
 
Example 7
Source File: CentralAuthenticationServiceImpl.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
/**
 * @throws IllegalArgumentException if ticketGrantingTicketId or service are null.
 */
@Audit(
    action="SERVICE_TICKET",
    actionResolverName="GRANT_SERVICE_TICKET_RESOLVER",
    resourceResolverName="GRANT_SERVICE_TICKET_RESOURCE_RESOLVER")
@Profiled(tag="GRANT_SERVICE_TICKET", logFailuresSeparately = false)
@Transactional(readOnly = false)
public String grantServiceTicket(
        final String ticketGrantingTicketId, final Service service, final Credential... credentials)
        throws AuthenticationException, TicketException {
    Assert.notNull(ticketGrantingTicketId, "ticketGrantingticketId cannot be null");
    Assert.notNull(service, "service cannot be null");

    final TicketGrantingTicket ticketGrantingTicket = this.ticketRegistry.getTicket(ticketGrantingTicketId, TicketGrantingTicket.class);

    if (ticketGrantingTicket == null) {
        logger.debug("TicketGrantingTicket [{}] cannot be found in the ticket registry.", ticketGrantingTicketId);
        throw new InvalidTicketException(ticketGrantingTicketId);
    }

    synchronized (ticketGrantingTicket) {
        if (ticketGrantingTicket.isExpired()) {
            this.ticketRegistry.deleteTicket(ticketGrantingTicketId);
            logger.debug("TicketGrantingTicket[{}] has expired and is now deleted from the ticket registry.", ticketGrantingTicketId);
            throw new InvalidTicketException(ticketGrantingTicketId);
        }
    }

    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    verifyRegisteredServiceProperties(registeredService, service);
    
    if (!registeredService.isSsoEnabled() && credentials == null
        && ticketGrantingTicket.getCountOfUses() > 0) {
        logger.warn("ServiceManagement: Service [{}] is not allowed to use SSO.", service.getId());
        throw new UnauthorizedSsoServiceException();
    }

    //CAS-1019
    final List<Authentication> authns = ticketGrantingTicket.getChainedAuthentications();
    if(authns.size() > 1) {
        if (!registeredService.isAllowedToProxy()) {
            final String message = String.
                    format("ServiceManagement: Proxy attempt by service [%s] (registered service [%s]) is not allowed.",
                    service.getId(), registeredService.toString());
            logger.warn(message);
            throw new UnauthorizedProxyingException(message);
        }
    }

    if (credentials != null) {
        final Authentication current = this.authenticationManager.authenticate(credentials);
        final Authentication original = ticketGrantingTicket.getAuthentication();
        if (!current.getPrincipal().equals(original.getPrincipal())) {
            throw new MixedPrincipalException(current, current.getPrincipal(), original.getPrincipal());
        }
        ticketGrantingTicket.getSupplementalAuthentications().add(current);
    }

    // Perform security policy check by getting the authentication that satisfies the configured policy
    // This throws if no suitable policy is found
    getAuthenticationSatisfiedByPolicy(ticketGrantingTicket.getRoot(), new ServiceContext(service, registeredService));

    final String uniqueTicketIdGenKey = service.getClass().getName();
    if (!this.uniqueTicketIdGeneratorsForService.containsKey(uniqueTicketIdGenKey)) {
        logger.warn("Cannot create service ticket because the key [{}] for service [{}] is not linked to a ticket id generator",
                uniqueTicketIdGenKey, service.getId());
        throw new UnauthorizedSsoServiceException();
    }
    
    final UniqueTicketIdGenerator serviceTicketUniqueTicketIdGenerator =
            this.uniqueTicketIdGeneratorsForService.get(uniqueTicketIdGenKey);

    final String generatedServiceTicketId = serviceTicketUniqueTicketIdGenerator.getNewTicketId(ServiceTicket.PREFIX);
    logger.debug("Generated service ticket id [{}] for ticket granting ticket [{}]",
            generatedServiceTicketId, ticketGrantingTicket.getId());
    
    final ServiceTicket serviceTicket = ticketGrantingTicket.grantServiceTicket(generatedServiceTicketId, service,
            this.serviceTicketExpirationPolicy, credentials != null);

    this.serviceTicketRegistry.addTicket(serviceTicket);

    if (logger.isInfoEnabled()) {
        final List<Authentication> authentications = serviceTicket.getGrantingTicket().getChainedAuthentications();
        final String formatString = "Granted %s ticket [%s] for service [%s] for user [%s]";
        final String type;
        final String principalId = authentications.get(authentications.size() - 1).getPrincipal().getId();

        if (authentications.size() == 1) {
            type = "service";
        } else {
            type = "proxy";
        }

        logger.info(String.format(formatString, type, serviceTicket.getId(), service.getId(), principalId));
    }

    return serviceTicket.getId();
}
 
Example 8
Source File: CentralAuthenticationServiceImpl.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
/**
 * @throws IllegalArgumentException if the ServiceTicketId or the Service
 * are null.
 */
@Audit(
    action="SERVICE_TICKET_VALIDATE",
    actionResolverName="VALIDATE_SERVICE_TICKET_RESOLVER",
    resourceResolverName="VALIDATE_SERVICE_TICKET_RESOURCE_RESOLVER")
@Profiled(tag="VALIDATE_SERVICE_TICKET", logFailuresSeparately = false)
@Transactional(readOnly = false)
public Assertion validateServiceTicket(final String serviceTicketId, final Service service) throws TicketException {
    Assert.notNull(serviceTicketId, "serviceTicketId cannot be null");
    Assert.notNull(service, "service cannot be null");
 
    final ServiceTicket serviceTicket =  this.serviceTicketRegistry.getTicket(serviceTicketId, ServiceTicket.class);

    if (serviceTicket == null) {
        logger.info("ServiceTicket [{}] does not exist.", serviceTicketId);
        throw new InvalidTicketException(serviceTicketId);
    }

    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);

    verifyRegisteredServiceProperties(registeredService, serviceTicket.getService());
    
    try {
        synchronized (serviceTicket) {
            if (serviceTicket.isExpired()) {
                logger.info("ServiceTicket [{}] has expired.", serviceTicketId);
                throw new InvalidTicketException(serviceTicketId);
            }

            if (!serviceTicket.isValidFor(service)) {
                logger.error("ServiceTicket [{}] with service [{}] does not match supplied service [{}]",
                        serviceTicketId, serviceTicket.getService().getId(), service);
                throw new TicketValidationException(serviceTicket.getService());
            }
        }

        final TicketGrantingTicket root = serviceTicket.getGrantingTicket().getRoot();
        final Authentication authentication = getAuthenticationSatisfiedByPolicy(
                root, new ServiceContext(serviceTicket.getService(), registeredService));
        final Principal principal = authentication.getPrincipal();

        Map<String, Object> attributesToRelease = this.defaultAttributeFilter.filter(principal.getId(),
                principal.getAttributes(), registeredService);
        if (registeredService.getAttributeFilter() != null) {
            attributesToRelease = registeredService.getAttributeFilter().filter(principal.getId(),
                    attributesToRelease, registeredService);
        }

        final String principalId = determinePrincipalIdForRegisteredService(principal, registeredService, serviceTicket);
        final Principal modifiedPrincipal = new SimplePrincipal(principalId, attributesToRelease);
        final AuthenticationBuilder builder = AuthenticationBuilder.newInstance(authentication);
        builder.setPrincipal(modifiedPrincipal);

        return new ImmutableAssertion(
                builder.build(),
                serviceTicket.getGrantingTicket().getChainedAuthentications(),
                serviceTicket.getService(),
                serviceTicket.isFromNewLogin());
    } finally {
        if (serviceTicket.isExpired()) {
            this.serviceTicketRegistry.deleteTicket(serviceTicketId);
        }
    }
}
 
Example 9
Source File: MultiFactorCredentials.java    From cas-mfa with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an instance of the {@link net.unicon.cas.mfa.authentication.CompositeAuthentication} object that collects
 * and harmonizes all principal and authentication attributes into one context.
 *
 * <p>Principal attributes are merged from all principals that are already resolved in the authentication chain.
 * Attributes with the same name that belong to the same principal are merged into one, with the latter value
 * overwriting the first. The established principal will be one that is based of {@link Principal}.</p>
 *
 * <p>Authentication attributes are merged from all authentications that make up the chain.
 * The merging strategy is such that duplicate attribute names are grouped together into an instance of
 * a {@link Collection} implementation and preserved.
 * @return an instance of {@link net.unicon.cas.mfa.authentication.CompositeAuthentication}
 */
public final Authentication getAuthentication() {
    if (!isEmpty()) {
        /**
         * Principal id is and must be enforced to be the same for all authentication contexts.
         * Based on that restriction, it's safe to simply grab the first principal id in the chain
         * when composing the authentication chain for the caller.
         */
        final String principalId = this.chainedAuthentication.get(0).getPrincipal().getId();
        final Map<String, Object> principalAttributes = new HashMap<>();

        final Map<String, Object> authenticationAttributes = new HashMap<>();

        final List<CredentialMetaData> credentials = new ArrayList<>();
        final Map<String, HandlerResult> successes = new LinkedHashMap<>();
        final Map<String, Class<? extends Exception>> failures = new LinkedHashMap<>();

        for (final Authentication authn : this.chainedAuthentication) {
            final Principal authenticatedPrincipal = authn.getPrincipal();
            principalAttributes.putAll(authenticatedPrincipal.getAttributes());

            credentials.addAll(authn.getCredentials());
            successes.putAll(authn.getSuccesses());
            failures.putAll(authn.getFailures());

            for (final String attrName : authn.getAttributes().keySet()) {
                if (!authenticationAttributes.containsKey(attrName)) {
                    authenticationAttributes.put(attrName, authn.getAttributes().get(attrName));
                } else {
                    final Object oldValue = authenticationAttributes.remove(attrName);
                    final Collection<Object> listOfValues = MultiFactorUtils.convertValueToCollection(oldValue);

                    listOfValues.add(authn.getAttributes().get(attrName));
                    authenticationAttributes.put(attrName, listOfValues);
                }
            }
        }
        final Principal compositePrincipal = principalFactory.createPrincipal(principalId, principalAttributes);
        final DefaultCompositeAuthentication finalAuth =
                new DefaultCompositeAuthentication(compositePrincipal,
                        authenticationAttributes, credentials, successes, failures);

        return finalAuth;
    }
    return null;
}
 
Example 10
Source File: DefaultAuthenticationSupport.java    From cas-mfa with Apache License 2.0 4 votes vote down vote up
@Override
/** {@inheritDoc} */
public Principal getAuthenticatedPrincipalFrom(final String ticketGrantingTicketId) throws RuntimeException {
    final Authentication auth = getAuthenticationFrom(ticketGrantingTicketId);
    return auth == null ? null : auth.getPrincipal();
}
 
Example 11
Source File: MultiFactorCredentialsTests.java    From cas-mfa with Apache License 2.0 4 votes vote down vote up
@Test
public void testCompositeAuthenticationAndPrincipalAttributes() {
    final Map attributes1 = new HashMap();
    attributes1.put("attr1", "attr2");
    attributes1.put("uid", "username");

    final Principal firstPrincipal =  new DefaultPrincipalFactory().createPrincipal("casuser", attributes1);

    final Authentication firstAuthentication = mock(Authentication.class);
    when(firstAuthentication.getPrincipal()).thenReturn(firstPrincipal);
    when(firstAuthentication.getAttributes())
        .thenReturn(Collections.singletonMap(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD,
                (Object) "first_method"));

    final Map attributes2 = new HashMap();
    attributes2.put("attr1", "attr3");
    attributes2.put("cn", "commonName");

    final Principal secondPrincipal =  new DefaultPrincipalFactory().createPrincipal("casuser", attributes2);

    final Authentication secondAuthentication = mock(Authentication.class);
    when(secondAuthentication.getPrincipal()).thenReturn(secondPrincipal);
    when(secondAuthentication.getAttributes())
        .thenReturn(Collections.singletonMap(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD,
            (Object) "second_method"));

    final MultiFactorCredentials c = new MultiFactorCredentials();
    c.addAuthenticationToChain(firstAuthentication);
    c.addAuthenticationToChain(secondAuthentication);
    assertEquals(2, c.countChainedAuthentications());

    final Authentication authn = c.getAuthentication();
    assertNotNull(authn);
    assertTrue(authn.getPrincipal().equals(firstPrincipal));
    assertTrue(authn.getPrincipal().equals(secondPrincipal));

    final Principal thePrincipal = authn.getPrincipal();
    assertEquals(thePrincipal.getAttributes().size(), 3);

    assertTrue(thePrincipal.getAttributes().containsKey("attr1"));
    assertTrue(thePrincipal.getAttributes().containsKey("uid"));
    assertTrue(thePrincipal.getAttributes().containsKey("cn"));
    assertEquals(thePrincipal.getAttributes().get("attr1"), "attr3");

    assertEquals(authn.getAttributes().size(), 1);

    final Set set = new HashSet(Arrays.asList("first_method", "second_method"));
    assertEquals(authn.getAttributes().get(MultiFactorAuthenticationSupportingWebApplicationService.CONST_PARAM_AUTHN_METHOD),
            set);
}