Search in sources :

Example 51 with Principal

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

the class OAuth20ProfileControllerTests method verifyExpiredAccessToken.

@Test
public void verifyExpiredAccessToken() throws Exception {
    final Principal principal = CoreAuthenticationTestUtils.getPrincipal(ID, new HashMap<>());
    final Authentication authentication = getAuthentication(principal);
    final DefaultAccessTokenFactory expiringAccessTokenFactory = new DefaultAccessTokenFactory(new AlwaysExpiresExpirationPolicy());
    final AccessToken accessToken = expiringAccessTokenFactory.create(RegisteredServiceTestUtils.getService(), authentication, new MockTicketGrantingTicket("casuser"), new ArrayList<>());
    this.ticketRegistry.addTicket(accessToken);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuth20Constants.PROFILE_URL);
    mockRequest.setParameter(OAuth20Constants.ACCESS_TOKEN, accessToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final ResponseEntity<String> entity = oAuth20ProfileController.handleRequest(mockRequest, mockResponse);
    assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
    assertEquals(CONTENT_TYPE, mockResponse.getContentType());
    assertTrue(entity.getBody().contains(OAuth20Constants.EXPIRED_ACCESS_TOKEN));
}
Also used : MockTicketGrantingTicket(org.apereo.cas.mock.MockTicketGrantingTicket) Authentication(org.apereo.cas.authentication.Authentication) DefaultAccessTokenFactory(org.apereo.cas.ticket.accesstoken.DefaultAccessTokenFactory) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AlwaysExpiresExpirationPolicy(org.apereo.cas.ticket.support.AlwaysExpiresExpirationPolicy) Principal(org.apereo.cas.authentication.principal.Principal) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 52 with Principal

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

the class SyncopeAuthenticationHandler method authenticateUsernamePasswordInternal.

@Override
protected AuthenticationHandlerExecutionResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential c, final String originalPassword) throws GeneralSecurityException {
    try {
        final String syncopeUrl = StringUtils.appendIfMissing(this.syncopeUrl, "/rest/users/self");
        final HttpResponse response = HttpUtils.executeGet(syncopeUrl, c.getUsername(), c.getPassword(), new HashMap<>(), CollectionUtils.wrap("X-Syncope-Domain", this.syncopeDomain));
        LOGGER.debug("Received http response status as [{}]", response.getStatusLine());
        if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            final String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
            LOGGER.debug("Received user object as [{}]", result);
            final UserTO user = this.objectMapper.readValue(result, UserTO.class);
            if (user.isSuspended()) {
                throw new AccountDisabledException("Could not authenticate forbidden account for " + c.getUsername());
            }
            if (user.isMustChangePassword()) {
                throw new AccountPasswordMustChangeException("Account password must change for " + c.getUsername());
            }
            final Principal principal = this.principalFactory.createPrincipal(user.getUsername(), buildSyncopeUserAttributes(user));
            return createHandlerResult(c, principal, new ArrayList<>());
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    throw new FailedLoginException("Could not authenticate account for " + c.getUsername());
}
Also used : FailedLoginException(javax.security.auth.login.FailedLoginException) UserTO(org.apache.syncope.common.lib.to.UserTO) HttpResponse(org.apache.http.HttpResponse) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) Principal(org.apereo.cas.authentication.principal.Principal) GeneralSecurityException(java.security.GeneralSecurityException) FailedLoginException(javax.security.auth.login.FailedLoginException) AccountDisabledException(org.apereo.cas.authentication.exceptions.AccountDisabledException) AccountPasswordMustChangeException(org.apereo.cas.authentication.exceptions.AccountPasswordMustChangeException)

Example 53 with Principal

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

the class GroovyScriptInterruptInquirer method inquire.

@Override
public InterruptResponse inquire(final Authentication authentication, final RegisteredService registeredService, final Service service) {
    if (ResourceUtils.doesResourceExist(resource)) {
        final Principal principal = authentication.getPrincipal();
        final Map<String, Object> attributes = new LinkedHashMap<>(principal.getAttributes());
        attributes.putAll(authentication.getAttributes());
        final Object[] args = { principal.getId(), attributes, service != null ? service.getId() : null, LOGGER };
        return ScriptingUtils.executeGroovyScript(resource, args, InterruptResponse.class);
    }
    return new InterruptResponse(false);
}
Also used : Principal(org.apereo.cas.authentication.principal.Principal) LinkedHashMap(java.util.LinkedHashMap)

Example 54 with Principal

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

the class BaseOidcScopeAttributeReleasePolicy method getAttributesInternal.

@Override
public Map<String, Object> getAttributesInternal(final Principal principal, final Map<String, Object> attributes, final RegisteredService service) {
    final ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
    if (applicationContext == null) {
        LOGGER.warn("Could not locate the application context to process attributes");
        return new HashMap<>();
    }
    final Map<String, Object> resolvedAttributes = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    resolvedAttributes.putAll(attributes);
    final Map<String, Object> attributesToRelease = new HashMap<>(resolvedAttributes.size());
    LOGGER.debug("Attempting to map and filter claims based on resolved attributes [{}]", resolvedAttributes);
    final CasConfigurationProperties properties = applicationContext.getBean(CasConfigurationProperties.class);
    final List<String> supportedClaims = properties.getAuthn().getOidc().getClaims();
    final Set<String> allowedClaims = new HashSet<>(getAllowedAttributes());
    allowedClaims.retainAll(supportedClaims);
    LOGGER.debug("[{}] is designed to allow claims [{}] for scope [{}]. After cross-checking with " + "supported claims [{}], the final collection of allowed attributes is [{}]", getClass().getSimpleName(), getAllowedAttributes(), getScopeName(), supportedClaims, allowedClaims);
    allowedClaims.stream().map(claim -> mapClaimToAttribute(claim, resolvedAttributes)).filter(p -> p.getValue() != null).forEach(p -> attributesToRelease.put(p.getKey(), p.getValue()));
    return attributesToRelease;
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) Setter(lombok.Setter) Getter(lombok.Getter) OidcAttributeToScopeClaimMapper(org.apereo.cas.oidc.claims.mapping.OidcAttributeToScopeClaimMapper) Set(java.util.Set) HashMap(java.util.HashMap) EqualsAndHashCode(lombok.EqualsAndHashCode) ApplicationContext(org.springframework.context.ApplicationContext) RegisteredService(org.apereo.cas.services.RegisteredService) AbstractRegisteredServiceAttributeReleasePolicy(org.apereo.cas.services.AbstractRegisteredServiceAttributeReleasePolicy) HashSet(java.util.HashSet) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Pair(org.apache.commons.lang3.tuple.Pair) TreeMap(java.util.TreeMap) Map(java.util.Map) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) ToString(lombok.ToString) Principal(org.apereo.cas.authentication.principal.Principal) ApplicationContextProvider(org.apereo.cas.util.spring.ApplicationContextProvider) ApplicationContext(org.springframework.context.ApplicationContext) HashMap(java.util.HashMap) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) ToString(lombok.ToString) TreeMap(java.util.TreeMap) HashSet(java.util.HashSet)

Example 55 with Principal

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

the class OidcIdTokenGeneratorService method produceIdTokenClaims.

/**
 * Produce id token claims jwt claims.
 *
 * @param request       the request
 * @param accessTokenId the access token id
 * @param timeout       the timeout
 * @param service       the service
 * @param profile       the user profile
 * @param context       the context
 * @param responseType  the response type
 * @return the jwt claims
 */
protected JwtClaims produceIdTokenClaims(final HttpServletRequest request, final AccessToken accessTokenId, final long timeout, final OidcRegisteredService service, final UserProfile profile, final J2EContext context, final OAuth20ResponseTypes responseType) {
    final Authentication authentication = accessTokenId.getAuthentication();
    final Principal principal = authentication.getPrincipal();
    final OidcProperties oidc = casProperties.getAuthn().getOidc();
    final JwtClaims claims = new JwtClaims();
    claims.setJwtId(getOAuthServiceTicket(accessTokenId.getTicketGrantingTicket()).getKey());
    claims.setIssuer(oidc.getIssuer());
    claims.setAudience(service.getClientId());
    final NumericDate expirationDate = NumericDate.now();
    expirationDate.addSeconds(timeout);
    claims.setExpirationTime(expirationDate);
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(oidc.getSkew());
    claims.setSubject(principal.getId());
    final MultifactorAuthenticationProperties mfa = casProperties.getAuthn().getMfa();
    final Map<String, Object> attributes = authentication.getAttributes();
    if (attributes.containsKey(mfa.getAuthenticationContextAttribute())) {
        final Collection<Object> val = CollectionUtils.toCollection(attributes.get(mfa.getAuthenticationContextAttribute()));
        claims.setStringClaim(OidcConstants.ACR, val.iterator().next().toString());
    }
    if (attributes.containsKey(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS)) {
        final Collection<Object> val = CollectionUtils.toCollection(attributes.get(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS));
        claims.setStringListClaim(OidcConstants.AMR, val.toArray(new String[] {}));
    }
    claims.setClaim(OAuth20Constants.STATE, attributes.get(OAuth20Constants.STATE));
    claims.setClaim(OAuth20Constants.NONCE, attributes.get(OAuth20Constants.NONCE));
    claims.setClaim(OidcConstants.CLAIM_AT_HASH, generateAccessTokenHash(accessTokenId, service));
    principal.getAttributes().entrySet().stream().filter(entry -> oidc.getClaims().contains(entry.getKey())).forEach(entry -> claims.setClaim(entry.getKey(), entry.getValue()));
    if (!claims.hasClaim(OidcConstants.CLAIM_PREFERRED_USERNAME)) {
        claims.setClaim(OidcConstants.CLAIM_PREFERRED_USERNAME, profile.getId());
    }
    return claims;
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) Arrays(java.util.Arrays) AlgorithmIdentifiers(org.jose4j.jws.AlgorithmIdentifiers) DigestUtils(org.apereo.cas.util.DigestUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationHandler(org.apereo.cas.authentication.AuthenticationHandler) MultifactorAuthenticationProperties(org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProperties) Authentication(org.apereo.cas.authentication.Authentication) OidcProperties(org.apereo.cas.configuration.model.support.oidc.OidcProperties) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) ServicesManager(org.apereo.cas.services.ServicesManager) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) OAuth20ResponseTypes(org.apereo.cas.support.oauth.OAuth20ResponseTypes) OidcConstants(org.apereo.cas.oidc.OidcConstants) Collection(java.util.Collection) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ProfileManager(org.pac4j.core.profile.ProfileManager) StandardCharsets(java.nio.charset.StandardCharsets) Pac4jUtils(org.apereo.cas.util.Pac4jUtils) Slf4j(lombok.extern.slf4j.Slf4j) MessageDigestAlgorithms(org.apache.commons.codec.digest.MessageDigestAlgorithms) NumericDate(org.jose4j.jwt.NumericDate) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) Stream(java.util.stream.Stream) JwtClaims(org.jose4j.jwt.JwtClaims) Service(org.apereo.cas.authentication.principal.Service) Entry(java.util.Map.Entry) J2EContext(org.pac4j.core.context.J2EContext) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Principal(org.apereo.cas.authentication.principal.Principal) EncodingUtils(org.apereo.cas.util.EncodingUtils) UserProfile(org.pac4j.core.profile.UserProfile) NumericDate(org.jose4j.jwt.NumericDate) JwtClaims(org.jose4j.jwt.JwtClaims) Authentication(org.apereo.cas.authentication.Authentication) OidcProperties(org.apereo.cas.configuration.model.support.oidc.OidcProperties) MultifactorAuthenticationProperties(org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProperties) Principal(org.apereo.cas.authentication.principal.Principal)

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