Search in sources :

Example 6 with OidcRegisteredService

use of org.apereo.cas.services.OidcRegisteredService 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 JwtClaims claims = new JwtClaims();
    claims.setJwtId(UUID.randomUUID().toString());
    claims.setIssuer(this.issuer);
    claims.setAudience(service.getClientId());
    final NumericDate expirationDate = NumericDate.now();
    expirationDate.addSeconds(timeout);
    claims.setExpirationTime(expirationDate);
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(this.skew);
    claims.setSubject(principal.getId());
    if (authentication.getAttributes().containsKey(casProperties.getAuthn().getMfa().getAuthenticationContextAttribute())) {
        final Collection<Object> val = CollectionUtils.toCollection(authentication.getAttributes().get(casProperties.getAuthn().getMfa().getAuthenticationContextAttribute()));
        claims.setStringClaim(OidcConstants.ACR, val.iterator().next().toString());
    }
    if (authentication.getAttributes().containsKey(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS)) {
        final Collection<Object> val = CollectionUtils.toCollection(authentication.getAttributes().get(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS));
        claims.setStringListClaim(OidcConstants.AMR, val.toArray(new String[] {}));
    }
    claims.setClaim(OAuthConstants.STATE, authentication.getAttributes().get(OAuthConstants.STATE));
    claims.setClaim(OAuthConstants.NONCE, authentication.getAttributes().get(OAuthConstants.NONCE));
    claims.setClaim(OidcConstants.CLAIM_AT_HASH, generateAccessTokenHash(accessTokenId, service));
    principal.getAttributes().entrySet().stream().filter(entry -> casProperties.getAuthn().getOidc().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) LoggerFactory(org.slf4j.LoggerFactory) DigestUtils(org.apereo.cas.util.DigestUtils) Autowired(org.springframework.beans.factory.annotation.Autowired) HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationHandler(org.apereo.cas.authentication.AuthenticationHandler) Authentication(org.apereo.cas.authentication.Authentication) CollectionUtils(org.apereo.cas.util.CollectionUtils) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) OAuth20ResponseTypes(org.apereo.cas.support.oauth.OAuth20ResponseTypes) Logger(org.slf4j.Logger) OidcConstants(org.apereo.cas.oidc.OidcConstants) Collection(java.util.Collection) OAuthConstants(org.apereo.cas.support.oauth.OAuthConstants) HttpServletResponse(javax.servlet.http.HttpServletResponse) UUID(java.util.UUID) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ProfileManager(org.pac4j.core.profile.ProfileManager) MessageDigestAlgorithms(org.apache.commons.codec.digest.MessageDigestAlgorithms) NumericDate(org.jose4j.jwt.NumericDate) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) JwtClaims(org.jose4j.jwt.JwtClaims) J2EContext(org.pac4j.core.context.J2EContext) Optional(java.util.Optional) Principal(org.apereo.cas.authentication.principal.Principal) EncodingUtils(org.apereo.cas.util.EncodingUtils) UserProfile(org.pac4j.core.profile.UserProfile) WebUtils(org.apereo.cas.web.support.WebUtils) NumericDate(org.jose4j.jwt.NumericDate) JwtClaims(org.jose4j.jwt.JwtClaims) Authentication(org.apereo.cas.authentication.Authentication) Principal(org.apereo.cas.authentication.principal.Principal)

Example 7 with OidcRegisteredService

use of org.apereo.cas.services.OidcRegisteredService in project cas by apereo.

the class OidcConfiguration method oidcServiceJsonWebKeystoreCache.

@Bean
public LoadingCache<OidcRegisteredService, Optional<RsaJsonWebKey>> oidcServiceJsonWebKeystoreCache() {
    final OidcProperties oidc = casProperties.getAuthn().getOidc();
    final LoadingCache<OidcRegisteredService, Optional<RsaJsonWebKey>> cache = CacheBuilder.newBuilder().maximumSize(1).expireAfterWrite(oidc.getJwksCacheInMinutes(), TimeUnit.MINUTES).build(oidcServiceJsonWebKeystoreCacheLoader());
    return cache;
}
Also used : Optional(java.util.Optional) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) OidcProperties(org.apereo.cas.configuration.model.support.oidc.OidcProperties) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Example 8 with OidcRegisteredService

use of org.apereo.cas.services.OidcRegisteredService in project cas by apereo.

the class OidcConsentApprovalViewResolver method prepareApprovalViewModel.

@Override
protected void prepareApprovalViewModel(final Map<String, Object> model, final J2EContext ctx, final OAuthRegisteredService svc) {
    super.prepareApprovalViewModel(model, ctx, svc);
    final OidcRegisteredService oidcRegisteredService = (OidcRegisteredService) svc;
    model.put("dynamic", oidcRegisteredService.isDynamicallyRegistered());
    model.put("dynamicTime", oidcRegisteredService.getDynamicRegistrationDateTime());
    final Set<String> supportedScopes = new HashSet<>(casProperties.getAuthn().getOidc().getScopes());
    supportedScopes.retainAll(oidcRegisteredService.getScopes());
    supportedScopes.retainAll(OAuthUtils.getRequestedScopes(ctx));
    model.put("scopes", supportedScopes);
}
Also used : OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) HashSet(java.util.HashSet)

Example 9 with OidcRegisteredService

use of org.apereo.cas.services.OidcRegisteredService in project cas by apereo.

the class OidcAuthorizeEndpointController method buildCallbackUrlForImplicitTokenResponseType.

private String buildCallbackUrlForImplicitTokenResponseType(final J2EContext context, final Authentication authentication, final Service service, final String redirectUri, final String clientId, final OAuth20ResponseTypes responseType) {
    try {
        final AccessToken accessToken = generateAccessToken(service, authentication, context);
        LOGGER.debug("Generated OAuth access token: [{}]", accessToken);
        final OidcRegisteredService oidcService = (OidcRegisteredService) OAuthUtils.getRegisteredOAuthService(this.getServicesManager(), clientId);
        final long timeout = casProperties.getTicket().getTgt().getTimeToKillInSeconds();
        final String idToken = this.idTokenGenerator.generate(context.getRequest(), context.getResponse(), accessToken, timeout, responseType, oidcService);
        LOGGER.debug("Generated id token [{}]", idToken);
        final List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair(OidcConstants.ID_TOKEN, idToken));
        return buildCallbackUrlResponseType(authentication, service, redirectUri, accessToken, params);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList)

Example 10 with OidcRegisteredService

use of org.apereo.cas.services.OidcRegisteredService in project cas by apereo.

the class OidcJwksEndpointController method handleRequestInternal.

/**
     * Handle request for jwk set.
     *
     * @param request  the request
     * @param response the response
     * @param model    the model
     * @return the jwk set
     * @throws Exception the exception
     */
@GetMapping(value = '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.JWKS_URL, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response, final Model model) throws Exception {
    Assert.notNull(this.jwksFile, "JWKS file cannot be undefined or null.");
    try {
        final String jsonJwks = IOUtils.toString(this.jwksFile.getInputStream(), StandardCharsets.UTF_8);
        final JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(jsonJwks);
        getServicesManager().getAllServices().stream().filter(s -> s instanceof OidcRegisteredService && StringUtils.isNotBlank(((OidcRegisteredService) s).getJwks())).forEach(Unchecked.consumer(s -> {
            final OidcRegisteredService service = (OidcRegisteredService) s;
            final Resource resource = this.resourceLoader.getResource(service.getJwks());
            final JsonWebKeySet set = new JsonWebKeySet(IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8));
            set.getJsonWebKeys().forEach(jsonWebKeySet::addJsonWebKey);
        }));
        final String body = jsonWebKeySet.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        return new ResponseEntity<>(body, HttpStatus.OK);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
Also used : Assert(com.stormpath.sdk.lang.Assert) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) LoggerFactory(org.slf4j.LoggerFactory) OAuth20Validator(org.apereo.cas.support.oauth.validator.OAuth20Validator) Autowired(org.springframework.beans.factory.annotation.Autowired) BaseOAuthWrapperController(org.apereo.cas.support.oauth.web.BaseOAuthWrapperController) StringUtils(org.apache.commons.lang3.StringUtils) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) Model(org.springframework.ui.Model) HttpServletRequest(javax.servlet.http.HttpServletRequest) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) GetMapping(org.springframework.web.bind.annotation.GetMapping) ServiceFactory(org.apereo.cas.authentication.principal.ServiceFactory) ServicesManager(org.apereo.cas.services.ServicesManager) Resource(org.springframework.core.io.Resource) Unchecked(org.jooq.lambda.Unchecked) Logger(org.slf4j.Logger) ResourceLoader(org.springframework.core.io.ResourceLoader) OAuth20ProfileScopeToAttributesFilter(org.apereo.cas.support.oauth.profile.OAuth20ProfileScopeToAttributesFilter) OidcConstants(org.apereo.cas.oidc.OidcConstants) JsonWebKey(org.jose4j.jwk.JsonWebKey) MediaType(org.springframework.http.MediaType) HttpServletResponse(javax.servlet.http.HttpServletResponse) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) StandardCharsets(java.nio.charset.StandardCharsets) IOUtils(org.apache.commons.io.IOUtils) AccessTokenFactory(org.apereo.cas.ticket.accesstoken.AccessTokenFactory) HttpStatus(org.springframework.http.HttpStatus) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) ResponseEntity(org.springframework.http.ResponseEntity) ResponseEntity(org.springframework.http.ResponseEntity) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) Resource(org.springframework.core.io.Resource) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

OidcRegisteredService (org.apereo.cas.services.OidcRegisteredService)14 ArrayList (java.util.ArrayList)3 Optional (java.util.Optional)3 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)3 URL (java.net.URL)2 StandardCharsets (java.nio.charset.StandardCharsets)2 HashMap (java.util.HashMap)2 HashSet (java.util.HashSet)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 IOUtils (org.apache.commons.io.IOUtils)2 StringUtils (org.apache.commons.lang3.StringUtils)2 Principal (org.apereo.cas.authentication.principal.Principal)2 CasConfigurationProperties (org.apereo.cas.configuration.CasConfigurationProperties)2 RegisteredServiceEditBean (org.apereo.cas.mgmt.services.web.beans.RegisteredServiceEditBean)2 RegisteredServiceOAuthTypeEditBean (org.apereo.cas.mgmt.services.web.beans.RegisteredServiceOAuthTypeEditBean)2 RegisteredServicePublicKeyEditBean (org.apereo.cas.mgmt.services.web.beans.RegisteredServicePublicKeyEditBean)2 RegisteredServiceSamlTypeEditBean (org.apereo.cas.mgmt.services.web.beans.RegisteredServiceSamlTypeEditBean)2 OidcConstants (org.apereo.cas.oidc.OidcConstants)2 DefaultRegisteredServiceProperty (org.apereo.cas.services.DefaultRegisteredServiceProperty)2