Search in sources :

Example 46 with Service

use of org.apereo.cas.authentication.principal.Service 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)

Example 47 with Service

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

the class OidcRegisteredServiceUIAction method doExecute.

@Override
protected Event doExecute(final RequestContext requestContext) {
    Service service = WebUtils.getService(requestContext);
    if (service != null) {
        service = serviceSelectionStrategy.resolveServiceFrom(service);
        final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
        RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(service, registeredService);
        if (registeredService instanceof OidcRegisteredService) {
            final OidcRegisteredService oauthService = OidcRegisteredService.class.cast(registeredService);
            WebUtils.putServiceUserInterfaceMetadata(requestContext, new DefaultRegisteredServiceUserInterfaceInfo(oauthService));
        }
    }
    return success();
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) Service(org.apereo.cas.authentication.principal.Service) DefaultRegisteredServiceUserInterfaceInfo(org.apereo.cas.web.flow.services.DefaultRegisteredServiceUserInterfaceInfo)

Example 48 with Service

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

the class DefaultSingleSignOnParticipationStrategy method isParticipating.

@Override
public boolean isParticipating(final RequestContext ctx) {
    if (renewEnabled && ctx.getRequestParameters().contains(CasProtocolConstants.PARAMETER_RENEW)) {
        LOGGER.debug("[{}] is specified for the request. The authentication session will be considered renewed.", CasProtocolConstants.PARAMETER_RENEW);
        return this.createSsoSessionCookieOnRenewAuthentications;
    }
    final Authentication authentication = WebUtils.getAuthentication(ctx);
    final Service service = WebUtils.getService(ctx);
    if (service != null) {
        final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
        if (registeredService != null) {
            final Authentication ca = AuthenticationCredentialsThreadLocalBinder.getCurrentAuthentication();
            try {
                AuthenticationCredentialsThreadLocalBinder.bindCurrent(authentication);
                final boolean isAllowedForSso = registeredService.getAccessStrategy().isServiceAccessAllowedForSso();
                LOGGER.debug("Located [{}] in registry. Service access to participate in SSO is set to [{}]", registeredService.getServiceId(), isAllowedForSso);
                return isAllowedForSso;
            } finally {
                AuthenticationCredentialsThreadLocalBinder.bindCurrent(ca);
            }
        }
    }
    return true;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) Authentication(org.apereo.cas.authentication.Authentication) Service(org.apereo.cas.authentication.principal.Service) RegisteredService(org.apereo.cas.services.RegisteredService)

Example 49 with Service

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

the class AbstractCasWebflowEventResolver method handleAuthenticationTransactionAndGrantTicketGrantingTicket.

/**
 * Handle authentication transaction and grant ticket granting ticket.
 *
 * @param context the context
 * @return the set
 */
protected Set<Event> handleAuthenticationTransactionAndGrantTicketGrantingTicket(final RequestContext context) {
    try {
        final Credential credential = getCredentialFromContext(context);
        AuthenticationResultBuilder builder = WebUtils.getAuthenticationResultBuilder(context);
        LOGGER.debug("Handling authentication transaction for credential [{}]", credential);
        final Service service = WebUtils.getService(context);
        builder = this.authenticationSystemSupport.handleAuthenticationTransaction(service, builder, credential);
        LOGGER.debug("Issuing ticket-granting tickets for service [{}]", service);
        return CollectionUtils.wrapSet(grantTicketGrantingTicketToAuthenticationResult(context, builder, service));
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        final MessageContext messageContext = context.getMessageContext();
        messageContext.addMessage(new MessageBuilder().error().code(DEFAULT_MESSAGE_BUNDLE_PREFIX.concat(e.getClass().getSimpleName())).build());
        return CollectionUtils.wrapSet(new EventFactorySupport().error(this));
    }
}
Also used : Credential(org.apereo.cas.authentication.Credential) MessageBuilder(org.springframework.binding.message.MessageBuilder) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) MessageContext(org.springframework.binding.message.MessageContext) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) EventFactorySupport(org.springframework.webflow.action.EventFactorySupport)

Example 50 with Service

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

the class ServiceTicketRequestWebflowEventResolver method grantServiceTicket.

/**
 * Grant service ticket for the given credential based on the service and tgt
 * that are found in the request context.
 *
 * @param context the context
 * @return the resulting event. Warning, authentication failure or error.
 * @since 4.1.0
 */
protected Event grantServiceTicket(final RequestContext context) {
    final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
    final Credential credential = getCredentialFromContext(context);
    try {
        final Service service = WebUtils.getService(context);
        final Authentication authn = ticketRegistrySupport.getAuthenticationFrom(ticketGrantingTicketId);
        final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
        if (authn != null && registeredService != null) {
            LOGGER.debug("Enforcing access strategy policies for registered service [{}] and principal [{}]", registeredService, authn.getPrincipal());
            final AuditableContext audit = AuditableContext.builder().service(service).authentication(authn).registeredService(registeredService).retrievePrincipalAttributesFromReleasePolicy(Boolean.TRUE).build();
            final AuditableExecutionResult accessResult = this.registeredServiceAccessStrategyEnforcer.execute(audit);
            accessResult.throwExceptionIfNeeded();
        }
        final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, credential);
        final ServiceTicket serviceTicketId = this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId, service, authenticationResult);
        WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
        WebUtils.putWarnCookieIfRequestParameterPresent(this.warnCookieGenerator, context);
        return newEvent(CasWebflowConstants.TRANSITION_ID_WARN);
    } catch (final AuthenticationException | AbstractTicketException e) {
        return newEvent(CasWebflowConstants.TRANSITION_ID_AUTHENTICATION_FAILURE, e);
    }
}
Also used : AuditableContext(org.apereo.cas.audit.AuditableContext) Credential(org.apereo.cas.authentication.Credential) RegisteredService(org.apereo.cas.services.RegisteredService) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) Authentication(org.apereo.cas.authentication.Authentication) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Aggregations

Service (org.apereo.cas.authentication.principal.Service)173 RegisteredService (org.apereo.cas.services.RegisteredService)67 Test (org.junit.Test)61 Authentication (org.apereo.cas.authentication.Authentication)47 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)44 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)42 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)35 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)32 WebApplicationService (org.apereo.cas.authentication.principal.WebApplicationService)29 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)21 AbstractWebApplicationService (org.apereo.cas.authentication.principal.AbstractWebApplicationService)18 HttpServletRequest (javax.servlet.http.HttpServletRequest)16 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)15 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)15 Credential (org.apereo.cas.authentication.Credential)13 Principal (org.apereo.cas.authentication.principal.Principal)13 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)13 MockTicketGrantingTicket (org.apereo.cas.mock.MockTicketGrantingTicket)12 TicketGrantingTicketImpl (org.apereo.cas.ticket.TicketGrantingTicketImpl)12 NeverExpiresExpirationPolicy (org.apereo.cas.ticket.support.NeverExpiresExpirationPolicy)12