Search in sources :

Example 66 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class BaseAcceptableUsagePolicyRepository method getPolicyMessageBundleCode.

/**
 * Gets policy message bundle code.
 *
 * @param requestContext the request context
 * @return the policy message bundle code
 */
protected String getPolicyMessageBundleCode(final RequestContext requestContext) {
    val registeredService = WebUtils.getRegisteredService(requestContext);
    if (registeredService != null && registeredService.getAcceptableUsagePolicy() != null && StringUtils.isNotBlank(registeredService.getAcceptableUsagePolicy().getMessageCode())) {
        return registeredService.getAcceptableUsagePolicy().getMessageCode();
    }
    if (StringUtils.isBlank(aupProperties.getCore().getAupPolicyTermsAttributeName())) {
        return null;
    }
    val principal = WebUtils.getAuthentication(requestContext).getPrincipal();
    val attributes = principal.getAttributes();
    if (!attributes.containsKey(aupProperties.getCore().getAupPolicyTermsAttributeName())) {
        LOGGER.trace("No attribute for policy terms is defined");
        return null;
    }
    val value = CollectionUtils.firstElement(attributes.get(aupProperties.getCore().getAupPolicyTermsAttributeName()));
    return value.map(v -> String.format("%s.%s", AcceptableUsagePolicyTerms.CODE, value.get())).orElse(null);
}
Also used : lombok.val(lombok.val) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) AcceptableUsagePolicyProperties(org.apereo.cas.configuration.model.support.aup.AcceptableUsagePolicyProperties) RequiredArgsConstructor(lombok.RequiredArgsConstructor) lombok.val(lombok.val) TicketRegistrySupport(org.apereo.cas.ticket.registry.TicketRegistrySupport) StringUtils(org.apache.commons.lang3.StringUtils) RequestContext(org.springframework.webflow.execution.RequestContext) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) AccessLevel(lombok.AccessLevel) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) Optional(java.util.Optional) Principal(org.apereo.cas.authentication.principal.Principal) WebUtils(org.apereo.cas.web.support.WebUtils)

Example 67 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class JcifsSpnegoAuthenticationHandler method doAuthentication.

@Override
@Synchronized
protected AuthenticationHandlerExecutionResult doAuthentication(final Credential credential) throws GeneralSecurityException {
    val spnegoCredential = (SpnegoCredential) credential;
    if (!this.ntlmAllowed && spnegoCredential.isNtlm()) {
        throw new FailedLoginException("NTLM not allowed");
    }
    var principal = (java.security.Principal) null;
    var nextToken = (byte[]) null;
    val it = this.authentications.iterator();
    while (nextToken == null && it.hasNext()) {
        try {
            val authentication = it.next();
            authentication.reset();
            LOGGER.debug("Processing SPNEGO authentication");
            authentication.process(spnegoCredential.getInitToken());
            principal = authentication.getPrincipal();
            LOGGER.debug("Authenticated SPNEGO principal [{}]. Retrieving the next token for authentication...", Optional.ofNullable(principal).map(java.security.Principal::getName).orElse(null));
            nextToken = authentication.getNextToken();
        } catch (final jcifs.spnego.AuthenticationException e) {
            LOGGER.debug("Processing SPNEGO authentication failed with exception", e);
            throw new FailedLoginException(e.getMessage());
        }
    }
    if (nextToken != null) {
        LOGGER.debug("Setting nextToken in credential");
        spnegoCredential.setNextToken(nextToken);
    } else {
        LOGGER.debug("nextToken is null");
    }
    var success = false;
    if (principal != null) {
        if (spnegoCredential.isNtlm()) {
            LOGGER.debug("NTLM Credential is valid for user [{}]", principal.getName());
        } else {
            LOGGER.debug("Kerberos Credential is valid for user [{}]", principal.getName());
        }
        spnegoCredential.setPrincipal(getPrincipal(principal.getName(), spnegoCredential.isNtlm()));
        success = true;
    }
    if (!success) {
        throw new FailedLoginException("Principal is null, the processing of the SPNEGO Token failed");
    }
    return new DefaultAuthenticationHandlerExecutionResult(this, new BasicCredentialMetaData(credential), spnegoCredential.getPrincipal());
}
Also used : lombok.val(lombok.val) SpnegoCredential(org.apereo.cas.support.spnego.authentication.principal.SpnegoCredential) FailedLoginException(javax.security.auth.login.FailedLoginException) DefaultAuthenticationHandlerExecutionResult(org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult) Principal(org.apereo.cas.authentication.principal.Principal) BasicCredentialMetaData(org.apereo.cas.authentication.metadata.BasicCredentialMetaData) Synchronized(lombok.Synchronized)

Example 68 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class OidcProfileScopeToAttributesFilter method filterAttributesByScope.

/**
 * Filter attributes by scope map.
 *
 * @param scopes            the scopes
 * @param principal         the principal
 * @param service           the service
 * @param registeredService the registered service
 * @param accessToken       the access token
 * @return the map
 */
protected Map<String, List<Object>> filterAttributesByScope(final Collection<String> scopes, final Principal principal, final Service service, final RegisteredService registeredService, final OAuth20AccessToken accessToken) {
    if (scopes.isEmpty()) {
        val attributes = principal.getAttributes();
        LOGGER.trace("No defined scopes are available to instruct attribute release policies for [{}]. " + "CAS will authorize the collection of resolved attributes [{}] for release to [{}]", registeredService.getServiceId(), attributes, service.getId());
        return attributes;
    }
    val attributes = new LinkedHashMap<String, List<Object>>();
    scopes.stream().distinct().filter(this.attributeReleasePolicies::containsKey).map(s -> {
        val policy = attributeReleasePolicies.get(s);
        val releasePolicyContext = RegisteredServiceAttributeReleasePolicyContext.builder().registeredService(registeredService).service(service).principal(principal).build();
        val policyAttr = policy.getAttributes(releasePolicyContext);
        LOGGER.debug("Calculated attributes [{}] via attribute release policy [{}]", policyAttr, policy.getName());
        return policyAttr;
    }).forEach(attributes::putAll);
    return attributes;
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) RegisteredServiceAttributeReleasePolicyContext(org.apereo.cas.services.RegisteredServiceAttributeReleasePolicyContext) OidcCustomScopeAttributeReleasePolicy(org.apereo.cas.oidc.claims.OidcCustomScopeAttributeReleasePolicy) Reflections(org.reflections.Reflections) BaseOidcScopeAttributeReleasePolicy(org.apereo.cas.oidc.claims.BaseOidcScopeAttributeReleasePolicy) LinkedHashMap(java.util.LinkedHashMap) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) DefaultOAuth20ProfileScopeToAttributesFilter(org.apereo.cas.support.oauth.profile.DefaultOAuth20ProfileScopeToAttributesFilter) FilterBuilder(org.reflections.util.FilterBuilder) Map(java.util.Map) ConfigurationBuilder(org.reflections.util.ConfigurationBuilder) LinkedHashSet(java.util.LinkedHashSet) Unchecked(org.jooq.lambda.Unchecked) ClassUtils(org.springframework.util.ClassUtils) OAuth20Utils(org.apereo.cas.support.oauth.util.OAuth20Utils) OidcConstants(org.apereo.cas.oidc.OidcConstants) Collection(java.util.Collection) lombok.val(lombok.val) RegisteredService(org.apereo.cas.services.RegisteredService) ClasspathHelper(org.reflections.util.ClasspathHelper) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken) OidcAttributeReleasePolicyFactory(org.apereo.cas.oidc.scopes.OidcAttributeReleasePolicyFactory) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) Service(org.apereo.cas.authentication.principal.Service) Principal(org.apereo.cas.authentication.principal.Principal) LinkedHashMap(java.util.LinkedHashMap)

Example 69 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class SendForgotUsernameInstructionsAction method sendForgotUsernameEmailToAccount.

/**
 * Send forgot username email to account.
 *
 * @param query          the query
 * @param requestContext the request context
 * @return the boolean
 */
protected boolean sendForgotUsernameEmailToAccount(final PasswordManagementQuery query, final RequestContext requestContext) {
    val parameters = CollectionUtils.<String, Object>wrap("email", query.getEmail());
    val credential = new BasicIdentifiableCredential();
    credential.setId(query.getUsername());
    val person = principalResolver.resolve(credential);
    FunctionUtils.doIf(person != null && !person.getClass().equals(NullPrincipal.class), principal -> {
        parameters.put("principal", principal);
        requestContext.getFlashScope().put(Principal.class.getName(), person);
    }).accept(person);
    val reset = casProperties.getAuthn().getPm().getForgotUsername().getMail();
    val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext);
    val body = EmailMessageBodyBuilder.builder().properties(reset).locale(Optional.ofNullable(request.getLocale())).parameters(parameters).build().produce();
    return this.communicationsManager.email(reset, query.getEmail(), body);
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) AuditPrincipalResolvers(org.apereo.cas.audit.AuditPrincipalResolvers) RequiredArgsConstructor(lombok.RequiredArgsConstructor) EmailValidator(org.apache.commons.validator.routines.EmailValidator) StringUtils(org.apache.commons.lang3.StringUtils) RequestContext(org.springframework.webflow.execution.RequestContext) AuditActionResolvers(org.apereo.cas.audit.AuditActionResolvers) CommunicationsManager(org.apereo.cas.notifications.CommunicationsManager) BasicIdentifiableCredential(org.apereo.cas.authentication.credential.BasicIdentifiableCredential) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) CasWebflowConstants(org.apereo.cas.web.flow.CasWebflowConstants) CollectionUtils(org.apereo.cas.util.CollectionUtils) NullPrincipal(org.apereo.cas.authentication.principal.NullPrincipal) Audit(org.apereo.inspektr.audit.annotation.Audit) PrincipalResolver(org.apereo.cas.authentication.principal.PrincipalResolver) lombok.val(lombok.val) EventFactorySupport(org.springframework.webflow.action.EventFactorySupport) Slf4j(lombok.extern.slf4j.Slf4j) PasswordManagementService(org.apereo.cas.pm.PasswordManagementService) EmailMessageBodyBuilder(org.apereo.cas.notifications.mail.EmailMessageBodyBuilder) AuditResourceResolvers(org.apereo.cas.audit.AuditResourceResolvers) AuditableActions(org.apereo.cas.audit.AuditableActions) Optional(java.util.Optional) PasswordManagementQuery(org.apereo.cas.pm.PasswordManagementQuery) Principal(org.apereo.cas.authentication.principal.Principal) WebUtils(org.apereo.cas.web.support.WebUtils) BaseCasWebflowAction(org.apereo.cas.web.flow.actions.BaseCasWebflowAction) Event(org.springframework.webflow.execution.Event) BasicIdentifiableCredential(org.apereo.cas.authentication.credential.BasicIdentifiableCredential)

Example 70 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class SurrogatePrincipalElectionStrategyTests method verifyOperation.

@Test
public void verifyOperation() {
    val strategy = new SurrogatePrincipalElectionStrategy();
    val attributes = CollectionUtils.wrap("formalName", CollectionUtils.wrapSet("cas"), "theName", CollectionUtils.wrapSet("user"), "sysuser", CollectionUtils.wrapSet("casuser"), "firstName", CollectionUtils.wrapSet("cas-first"), "lastName", CollectionUtils.wrapSet("cas-last"));
    val authentications = new ArrayList<Authentication>();
    val primaryAuth = CoreAuthenticationTestUtils.getAuthentication("casuser");
    authentications.add(primaryAuth);
    val attributeRepository = CoreAuthenticationTestUtils.getAttributeRepository();
    val surrogatePrincipal = buildSurrogatePrincipal("cas-surrogate", primaryAuth, attributeRepository);
    authentications.add(CoreAuthenticationTestUtils.getAuthentication(surrogatePrincipal));
    val principal = strategy.nominate(authentications, (Map) attributes);
    assertNotNull(principal);
    assertEquals("cas-surrogate", principal.getId());
    assertEquals(attributeRepository.getBackingMap().size(), principal.getAttributes().size());
    val result = attributeRepository.getBackingMap().keySet().stream().filter(key -> !principal.getAttributes().containsKey(key)).findAny();
    if (result.isPresent()) {
        fail();
    }
}
Also used : lombok.val(lombok.val) PrincipalFactoryUtils(org.apereo.cas.authentication.principal.PrincipalFactoryUtils) lombok.val(lombok.val) HashMap(java.util.HashMap) IPersonAttributeDao(org.apereo.services.persondir.IPersonAttributeDao) ArrayList(java.util.ArrayList) Test(org.junit.jupiter.api.Test) Mockito(org.mockito.Mockito) List(java.util.List) SimpleSurrogateAuthenticationService(org.apereo.cas.authentication.surrogate.SimpleSurrogateAuthenticationService) Map(java.util.Map) RegisteredServiceTestUtils(org.apereo.cas.services.RegisteredServiceTestUtils) CollectionUtils(org.apereo.cas.util.CollectionUtils) Assertions(org.junit.jupiter.api.Assertions) Principal(org.apereo.cas.authentication.principal.Principal) Tag(org.junit.jupiter.api.Tag) ServicesManager(org.apereo.cas.services.ServicesManager) ArrayList(java.util.ArrayList) Test(org.junit.jupiter.api.Test)

Aggregations

Principal (org.apereo.cas.authentication.principal.Principal)114 HashMap (java.util.HashMap)33 RegisteredService (org.apereo.cas.services.RegisteredService)31 Test (org.junit.Test)29 Authentication (org.apereo.cas.authentication.Authentication)26 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)26 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)26 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)25 Map (java.util.Map)23 Slf4j (lombok.extern.slf4j.Slf4j)23 lombok.val (lombok.val)19 List (java.util.List)15 StringUtils (org.apache.commons.lang3.StringUtils)15 OAuthCode (org.apereo.cas.ticket.code.OAuthCode)15 CollectionUtils (org.apereo.cas.util.CollectionUtils)15 ArrayList (java.util.ArrayList)14 Optional (java.util.Optional)14 Service (org.apereo.cas.authentication.principal.Service)14 Collection (java.util.Collection)11 Collectors (java.util.stream.Collectors)10