Search in sources :

Example 51 with WebContext

use of org.pac4j.core.context.WebContext in project cas by apereo.

the class OAuth20AuthorizationCodeGrantTypeTokenRequestValidator method validateInternal.

@Override
protected boolean validateInternal(final WebContext context, final String grantType, final ProfileManager manager, final UserProfile uProfile) {
    val clientId = uProfile.getId();
    val redirectUri = OAuth20Utils.getRequestParameter(context, OAuth20Constants.REDIRECT_URI);
    val code = OAuth20Utils.getRequestParameter(context, OAuth20Constants.CODE);
    LOGGER.debug("Locating registered service for client id [{}]", clientId);
    val registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(getConfigurationContext().getServicesManager(), clientId);
    RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(registeredService);
    LOGGER.debug("Received grant type [{}] with client id [{}] and redirect URI [{}]", grantType, clientId, redirectUri);
    val valid = redirectUri.isPresent() && code.isPresent() && OAuth20Utils.checkCallbackValid(registeredService, redirectUri.get());
    if (valid) {
        val token = getConfigurationContext().getTicketRegistry().getTicket(code.get(), OAuth20Code.class);
        if (token == null || token.isExpired()) {
            LOGGER.debug("Code [{}] is invalid or expired. Attempting to revoke access tokens issued to the code", code.get());
            val accessTokensByCode = getConfigurationContext().getTicketRegistry().getTickets(ticket -> ticket instanceof OAuth20AccessToken && StringUtils.equalsIgnoreCase(((OAuth20AccessToken) ticket).getToken(), code.get()));
            accessTokensByCode.forEach(Unchecked.consumer(ticket -> {
                LOGGER.debug("Removing access token [{}] issued via expired/unknown code [{}]", ticket.getId(), code.get());
                getConfigurationContext().getTicketRegistry().deleteTicket(ticket);
            }));
            LOGGER.warn("Request OAuth code [{}] is not found or has expired", code.get());
            return false;
        }
        val id = token.getService().getId();
        val codeRegisteredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(getConfigurationContext().getServicesManager(), id);
        val audit = AuditableContext.builder().service(token.getService()).authentication(token.getAuthentication()).registeredService(codeRegisteredService).build();
        val accessResult = getConfigurationContext().getRegisteredServiceAccessStrategyEnforcer().execute(audit);
        accessResult.throwExceptionIfNeeded();
        if (!registeredService.equals(codeRegisteredService)) {
            LOGGER.warn("OAuth code [{}] issued to service [{}] does not match [{}] provided, given the redirect URI [{}]", code, id, registeredService.getName(), redirectUri);
            return false;
        }
        if (!isGrantTypeSupportedBy(registeredService, grantType)) {
            LOGGER.warn("Requested grant type [{}] is not authorized by service definition [{}]", getGrantType(), registeredService.getServiceId());
            return false;
        }
        return true;
    }
    LOGGER.warn("Access token request cannot be validated for grant type [{}] and client id [{}] given the redirect URI [{}]", grantType, clientId, redirectUri);
    return false;
}
Also used : lombok.val(lombok.val) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) Unchecked(org.jooq.lambda.Unchecked) OAuth20Utils(org.apereo.cas.support.oauth.util.OAuth20Utils) AuditableContext(org.apereo.cas.audit.AuditableContext) OAuth20GrantTypes(org.apereo.cas.support.oauth.OAuth20GrantTypes) OAuth20ConfigurationContext(org.apereo.cas.support.oauth.web.endpoints.OAuth20ConfigurationContext) lombok.val(lombok.val) RegisteredServiceAccessStrategyUtils(org.apereo.cas.services.RegisteredServiceAccessStrategyUtils) StringUtils(org.apache.commons.lang3.StringUtils) ProfileManager(org.pac4j.core.profile.ProfileManager) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken) WebContext(org.pac4j.core.context.WebContext) Slf4j(lombok.extern.slf4j.Slf4j) OAuth20Code(org.apereo.cas.ticket.code.OAuth20Code) UserProfile(org.pac4j.core.profile.UserProfile)

Example 52 with WebContext

use of org.pac4j.core.context.WebContext in project cas by apereo.

the class BaseDelegatedAuthenticationController method configureWebContextForRegisteredService.

/**
 * Configure web context for registered service.
 *
 * @param webContext the web context
 * @param ticket     the ticket
 */
protected void configureWebContextForRegisteredService(final WebContext webContext, final TransientSessionTicket ticket) {
    val registeredService = configurationContext.getServicesManager().findServiceBy(ticket.getService());
    val audit = AuditableContext.builder().service(ticket.getService()).registeredService(registeredService).build();
    val result = configurationContext.getRegisteredServiceAccessStrategyEnforcer().execute(audit);
    result.throwExceptionIfNeeded();
    if (!registeredService.getProperties().isEmpty()) {
        val delegatedAuthnProperties = Arrays.stream(RegisteredServiceProperties.values()).filter(prop -> prop.isMemberOf(RegisteredServicePropertyGroups.DELEGATED_AUTHN)).collect(Collectors.toList());
        configureWebContextForRegisteredServiceProperties(registeredService, webContext, delegatedAuthnProperties);
        val saml2ServiceProperties = Arrays.stream(RegisteredServiceProperties.values()).filter(prop -> prop.isMemberOf(RegisteredServicePropertyGroups.DELEGATED_AUTHN_SAML2)).collect(Collectors.toList());
        configureWebContextForRegisteredServiceProperties(registeredService, webContext, saml2ServiceProperties);
        val oidcProperties = Arrays.stream(RegisteredServiceProperties.values()).filter(prop -> prop.isMemberOf(RegisteredServicePropertyGroups.DELEGATED_AUTHN_OIDC)).collect(Collectors.toList());
        configureWebContextForRegisteredServiceProperties(registeredService, webContext, oidcProperties);
    }
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) Getter(lombok.Getter) RegisteredServiceProperties(org.apereo.cas.services.RegisteredServiceProperty.RegisteredServiceProperties) RegisteredServicePropertyGroups(org.apereo.cas.services.RegisteredServiceProperty.RegisteredServicePropertyGroups) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Controller(org.springframework.stereotype.Controller) Pac4jConstants(org.pac4j.core.util.Pac4jConstants) WebContext(org.pac4j.core.context.WebContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) AccessLevel(lombok.AccessLevel) DynamicHtmlView(org.apereo.cas.web.view.DynamicHtmlView) RedirectView(org.springframework.web.servlet.view.RedirectView) IndirectClient(org.pac4j.core.client.IndirectClient) RedirectionActionBuilder(org.pac4j.core.redirect.RedirectionActionBuilder) TransientSessionTicket(org.apereo.cas.ticket.TransientSessionTicket) AuditableContext(org.apereo.cas.audit.AuditableContext) URIBuilder(org.apache.http.client.utils.URIBuilder) lombok.val(lombok.val) WithLocationAction(org.pac4j.core.exception.http.WithLocationAction) Collectors(java.util.stream.Collectors) RegisteredService(org.apereo.cas.services.RegisteredService) Slf4j(lombok.extern.slf4j.Slf4j) View(org.springframework.web.servlet.View) List(java.util.List) DelegatedClientAuthenticationConfigurationContext(org.apereo.cas.web.flow.DelegatedClientAuthenticationConfigurationContext) Optional(java.util.Optional) RedirectionAction(org.pac4j.core.exception.http.RedirectionAction) WithContentAction(org.pac4j.core.exception.http.WithContentAction) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator)

Example 53 with WebContext

use of org.pac4j.core.context.WebContext in project cas by apereo.

the class BaseDelegatedAuthenticationController method getRedirectionAction.

/**
 * Gets redirection action.
 *
 * @param client     the client
 * @param webContext the web context
 * @param ticket     the ticket
 * @return the redirection action
 */
protected Optional<RedirectionAction> getRedirectionAction(final IndirectClient client, final WebContext webContext, final TransientSessionTicket ticket) {
    val properties = ticket.getProperties();
    if (properties.containsKey(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN)) {
        webContext.setRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN, true);
    }
    if (properties.containsKey(RedirectionActionBuilder.ATTRIBUTE_PASSIVE)) {
        webContext.setRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_PASSIVE, true);
    }
    if (ticket.getService() != null) {
        configureWebContextForRegisteredService(webContext, ticket);
    }
    configurationContext.getDelegatedClientAuthenticationRequestCustomizers().stream().sorted(AnnotationAwareOrderComparator.INSTANCE).filter(c -> c.supports(client, webContext)).forEach(c -> c.customize(client, webContext));
    return client.getRedirectionActionBuilder().getRedirectionAction(webContext, configurationContext.getSessionStore());
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) Getter(lombok.Getter) RegisteredServiceProperties(org.apereo.cas.services.RegisteredServiceProperty.RegisteredServiceProperties) RegisteredServicePropertyGroups(org.apereo.cas.services.RegisteredServiceProperty.RegisteredServicePropertyGroups) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Controller(org.springframework.stereotype.Controller) Pac4jConstants(org.pac4j.core.util.Pac4jConstants) WebContext(org.pac4j.core.context.WebContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) AccessLevel(lombok.AccessLevel) DynamicHtmlView(org.apereo.cas.web.view.DynamicHtmlView) RedirectView(org.springframework.web.servlet.view.RedirectView) IndirectClient(org.pac4j.core.client.IndirectClient) RedirectionActionBuilder(org.pac4j.core.redirect.RedirectionActionBuilder) TransientSessionTicket(org.apereo.cas.ticket.TransientSessionTicket) AuditableContext(org.apereo.cas.audit.AuditableContext) URIBuilder(org.apache.http.client.utils.URIBuilder) lombok.val(lombok.val) WithLocationAction(org.pac4j.core.exception.http.WithLocationAction) Collectors(java.util.stream.Collectors) RegisteredService(org.apereo.cas.services.RegisteredService) Slf4j(lombok.extern.slf4j.Slf4j) View(org.springframework.web.servlet.View) List(java.util.List) DelegatedClientAuthenticationConfigurationContext(org.apereo.cas.web.flow.DelegatedClientAuthenticationConfigurationContext) Optional(java.util.Optional) RedirectionAction(org.pac4j.core.exception.http.RedirectionAction) WithContentAction(org.pac4j.core.exception.http.WithContentAction) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator)

Example 54 with WebContext

use of org.pac4j.core.context.WebContext in project cas by apereo.

the class OidcAuthenticationAuthorizeSecurityLogic method loadProfiles.

@Override
protected List<UserProfile> loadProfiles(final ProfileManager manager, final WebContext context, final SessionStore sessionStore, final List<Client> clients) {
    val prompts = OidcRequestSupport.getOidcPromptFromAuthorizationRequest(context);
    LOGGER.debug("Located OpenID Connect prompts from request as [{}]", prompts);
    val tooOld = OidcRequestSupport.getOidcMaxAgeFromAuthorizationRequest(context).map(maxAge -> manager.getProfile(BasicUserProfile.class).stream().anyMatch(profile -> OidcRequestSupport.isCasAuthenticationOldForMaxAgeAuthorizationRequest(context, profile))).orElse(Boolean.FALSE);
    return tooOld || prompts.contains(OidcConstants.PROMPT_LOGIN) ? new ArrayList<>(0) : super.loadProfiles(manager, context, sessionStore, clients);
}
Also used : lombok.val(lombok.val) OidcConstants(org.apereo.cas.oidc.OidcConstants) lombok.val(lombok.val) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) BasicUserProfile(org.pac4j.core.profile.BasicUserProfile) SessionStore(org.pac4j.core.context.session.SessionStore) ProfileManager(org.pac4j.core.profile.ProfileManager) ArrayList(java.util.ArrayList) OAuth20TicketGrantingTicketAwareSecurityLogic(org.apereo.cas.support.oauth.web.OAuth20TicketGrantingTicketAwareSecurityLogic) WebContext(org.pac4j.core.context.WebContext) OidcRequestSupport(org.apereo.cas.oidc.util.OidcRequestSupport) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) TicketRegistry(org.apereo.cas.ticket.registry.TicketRegistry) CasCookieBuilder(org.apereo.cas.web.cookie.CasCookieBuilder) Client(org.pac4j.core.client.Client) UserProfile(org.pac4j.core.profile.UserProfile)

Example 55 with WebContext

use of org.pac4j.core.context.WebContext in project cas by apereo.

the class OidcConsentApprovalViewResolver method prepareApprovalViewModel.

@Override
protected void prepareApprovalViewModel(final Map<String, Object> model, final WebContext webContext, final OAuthRegisteredService svc) throws Exception {
    super.prepareApprovalViewModel(model, webContext, svc);
    if (svc instanceof OidcRegisteredService) {
        val oidcRegisteredService = (OidcRegisteredService) svc;
        model.put("dynamic", oidcRegisteredService.isDynamicallyRegistered());
        model.put("dynamicTime", oidcRegisteredService.getDynamicRegistrationDateTime());
        val supportedScopes = new HashSet<>(casProperties.getAuthn().getOidc().getDiscovery().getScopes());
        supportedScopes.retainAll(oidcRegisteredService.getScopes());
        val requestedScopes = OAuth20Utils.getRequestedScopes(webContext);
        val userInfoClaims = OAuth20Utils.parseUserInfoRequestClaims(webContext);
        webContext.getRequestParameter(OidcConstants.REQUEST_URI).ifPresent(Unchecked.consumer(uri -> {
            val authzRequest = centralAuthenticationService.getTicket(uri, OidcPushedAuthorizationRequest.class);
            val uriFactory = (OidcPushedAuthorizationRequestFactory) centralAuthenticationService.getTicketFactory().get(OidcPushedAuthorizationRequest.class);
            val holder = uriFactory.toAccessTokenRequest(authzRequest);
            userInfoClaims.addAll(holder.getClaims().keySet());
            requestedScopes.addAll(holder.getScopes());
        }));
        supportedScopes.retainAll(requestedScopes);
        supportedScopes.add(OidcConstants.StandardScopes.OPENID.getScope());
        model.put("scopes", supportedScopes);
        model.put("userInfoClaims", userInfoClaims);
    }
}
Also used : lombok.val(lombok.val) CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) OAuth20ConsentApprovalViewResolver(org.apereo.cas.support.oauth.web.views.OAuth20ConsentApprovalViewResolver) Unchecked(org.jooq.lambda.Unchecked) OAuth20Utils(org.apereo.cas.support.oauth.util.OAuth20Utils) OidcConstants(org.apereo.cas.oidc.OidcConstants) lombok.val(lombok.val) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) SessionStore(org.pac4j.core.context.session.SessionStore) HashSet(java.util.HashSet) OidcPushedAuthorizationRequest(org.apereo.cas.oidc.ticket.OidcPushedAuthorizationRequest) WebContext(org.pac4j.core.context.WebContext) OidcRequestSupport(org.apereo.cas.oidc.util.OidcRequestSupport) Slf4j(lombok.extern.slf4j.Slf4j) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) Map(java.util.Map) OidcPushedAuthorizationRequestFactory(org.apereo.cas.oidc.ticket.OidcPushedAuthorizationRequestFactory) OidcPushedAuthorizationRequest(org.apereo.cas.oidc.ticket.OidcPushedAuthorizationRequest) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) HashSet(java.util.HashSet)

Aggregations

WebContext (org.pac4j.core.context.WebContext)58 Test (org.junit.Test)31 MockWebContext (org.pac4j.core.context.MockWebContext)15 Slf4j (lombok.extern.slf4j.Slf4j)11 J2EContext (org.pac4j.core.context.J2EContext)11 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)11 lombok.val (lombok.val)10 CommonProfile (org.pac4j.core.profile.CommonProfile)10 RedirectAction (org.pac4j.core.redirect.RedirectAction)10 Optional (java.util.Optional)9 Clients (org.pac4j.core.client.Clients)9 SessionStore (org.pac4j.core.context.session.SessionStore)8 JWT (com.nimbusds.jwt.JWT)7 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 Client (org.pac4j.core.client.Client)7 MockIndirectClient (org.pac4j.core.client.MockIndirectClient)7 UserProfile (org.pac4j.core.profile.UserProfile)7 SignedJWT (com.nimbusds.jwt.SignedJWT)6 StringUtils (org.apache.commons.lang3.StringUtils)6