Search in sources :

Example 6 with OAuth20AccessToken

use of org.apereo.cas.ticket.accesstoken.OAuth20AccessToken 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 7 with OAuth20AccessToken

use of org.apereo.cas.ticket.accesstoken.OAuth20AccessToken in project cas by apereo.

the class OidcIntrospectionEndpointController method createIntrospectionValidResponse.

@Override
protected OAuth20IntrospectionAccessTokenResponse createIntrospectionValidResponse(final OAuth20AccessToken ticket) {
    val r = super.createIntrospectionValidResponse(ticket);
    r.setIss(getConfigurationContext().getIssuerService().determineIssuer(Optional.empty()));
    FunctionUtils.doIf(r.isActive(), o -> r.setScope(String.join(" ", ticket.getScopes()))).accept(r);
    return r;
}
Also used : lombok.val(lombok.val) PostMapping(org.springframework.web.bind.annotation.PostMapping) OidcConstants(org.apereo.cas.oidc.OidcConstants) MediaType(org.springframework.http.MediaType) lombok.val(lombok.val) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken) OidcConfigurationContext(org.apereo.cas.oidc.OidcConfigurationContext) HttpStatus(org.springframework.http.HttpStatus) OAuth20IntrospectionEndpointController(org.apereo.cas.support.oauth.web.endpoints.OAuth20IntrospectionEndpointController) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuth20IntrospectionAccessTokenResponse(org.apereo.cas.support.oauth.web.response.introspection.OAuth20IntrospectionAccessTokenResponse) GetMapping(org.springframework.web.bind.annotation.GetMapping) Optional(java.util.Optional) ResponseEntity(org.springframework.http.ResponseEntity) JEEContext(org.pac4j.core.context.JEEContext)

Example 8 with OAuth20AccessToken

use of org.apereo.cas.ticket.accesstoken.OAuth20AccessToken in project cas by apereo.

the class OAuth20AuthorizeEndpointControllerTests method verifyTokenRedirectToClientApproved.

@Test
public void verifyTokenRedirectToClientApproved() throws Exception {
    clearAllServices();
    val mockRequest = new MockHttpServletRequest(HttpMethod.GET.name(), CONTEXT + OAuth20Constants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuth20Constants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuth20Constants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuth20Constants.RESPONSE_TYPE, OAuth20ResponseTypes.TOKEN.name().toLowerCase());
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    val mockResponse = new MockHttpServletResponse();
    val service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
    service.setBypassApprovalPrompt(false);
    this.servicesManager.save(service);
    val profile = new CasProfile();
    profile.setId(ID);
    val attributes = new HashMap<String, Object>();
    attributes.put(FIRST_NAME_ATTRIBUTE, FIRST_NAME);
    attributes.put(LAST_NAME_ATTRIBUTE, LAST_NAME);
    profile.addAttributes(attributes);
    val session = new MockHttpSession();
    mockRequest.setSession(session);
    val sessionStore = oAuth20AuthorizeEndpointController.getConfigurationContext().getSessionStore();
    val context = new JEEContext(mockRequest, mockResponse);
    val ticket = new MockTicketGrantingTicket("casuser");
    oAuth20AuthorizeEndpointController.getConfigurationContext().getTicketRegistry().addTicket(ticket);
    sessionStore.set(context, WebUtils.PARAMETER_TICKET_GRANTING_TICKET_ID, ticket.getId());
    sessionStore.set(context, Pac4jConstants.USER_PROFILES, CollectionUtils.wrapLinkedHashMap(profile.getClientName(), profile));
    sessionStore.set(context, OAuth20Constants.BYPASS_APPROVAL_PROMPT, "true");
    val modelAndView = oAuth20AuthorizeEndpointController.handleRequest(mockRequest, mockResponse);
    val view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    val redirectView = (RedirectView) view;
    val redirectUrl = redirectView.getUrl();
    assertNotNull(redirectUrl);
    assertTrue(redirectUrl.startsWith(REDIRECT_URI + "#access_token="));
    val code = StringUtils.substringBetween(redirectUrl, "#access_token=", "&token_type=bearer");
    val accessToken = (OAuth20AccessToken) this.ticketRegistry.getTicket(code);
    assertNotNull(accessToken);
    val principal = accessToken.getAuthentication().getPrincipal();
    assertEquals(ID, principal.getId());
    val principalAttributes = principal.getAttributes();
    assertEquals(attributes.size(), principalAttributes.size());
    assertEquals(FIRST_NAME, principalAttributes.get(FIRST_NAME_ATTRIBUTE).get(0));
}
Also used : lombok.val(lombok.val) CasProfile(org.pac4j.cas.profile.CasProfile) MockTicketGrantingTicket(org.apereo.cas.mock.MockTicketGrantingTicket) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) JEEContext(org.pac4j.core.context.JEEContext) RedirectView(org.springframework.web.servlet.view.RedirectView) MockHttpSession(org.springframework.mock.web.MockHttpSession) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 9 with OAuth20AccessToken

use of org.apereo.cas.ticket.accesstoken.OAuth20AccessToken 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 10 with OAuth20AccessToken

use of org.apereo.cas.ticket.accesstoken.OAuth20AccessToken in project cas by apereo.

the class OAuth20AccessTokenEndpointController method generateAccessTokenResponse.

/**
 * Generate access token response model and view.
 *
 * @param requestHolder the request holder
 * @param result        the result
 * @return the model and view
 */
protected ModelAndView generateAccessTokenResponse(final AccessTokenRequestContext requestHolder, final OAuth20TokenGeneratedResult result) {
    LOGGER.debug("Generating access token response for [{}]", result);
    val deviceRefreshInterval = Beans.newDuration(getConfigurationContext().getCasProperties().getAuthn().getOauth().getDeviceToken().getRefreshInterval()).getSeconds();
    val dtPolicy = getConfigurationContext().getDeviceTokenExpirationPolicy();
    val tokenResult = OAuth20AccessTokenResponseResult.builder().registeredService(requestHolder.getRegisteredService()).service(requestHolder.getService()).accessTokenTimeout(result.getAccessToken().map(OAuth20AccessToken::getExpiresIn).orElse(0L)).deviceRefreshInterval(deviceRefreshInterval).deviceTokenTimeout(dtPolicy.buildTicketExpirationPolicy().getTimeToLive()).responseType(result.getResponseType().orElse(OAuth20ResponseTypes.NONE)).casProperties(getConfigurationContext().getCasProperties()).generatedToken(result).grantType(result.getGrantType().orElse(OAuth20GrantTypes.NONE)).userProfile(requestHolder.getUserProfile()).build();
    return getConfigurationContext().getAccessTokenResponseGenerator().generate(tokenResult);
}
Also used : lombok.val(lombok.val) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken)

Aggregations

lombok.val (lombok.val)13 OAuth20AccessToken (org.apereo.cas.ticket.accesstoken.OAuth20AccessToken)13 JEEContext (org.pac4j.core.context.JEEContext)6 Slf4j (lombok.extern.slf4j.Slf4j)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 MockTicketGrantingTicket (org.apereo.cas.mock.MockTicketGrantingTicket)3 OidcConstants (org.apereo.cas.oidc.OidcConstants)3 OAuth20Utils (org.apereo.cas.support.oauth.util.OAuth20Utils)3 ResponseEntity (org.springframework.http.ResponseEntity)3 LinkedHashMap (java.util.LinkedHashMap)2 LinkedHashSet (java.util.LinkedHashSet)2 Optional (java.util.Optional)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 StringUtils (org.apache.commons.lang3.StringUtils)2 Principal (org.apereo.cas.authentication.principal.Principal)2 OidcConfigurationContext (org.apereo.cas.oidc.OidcConfigurationContext)2 OidcRegisteredService (org.apereo.cas.services.OidcRegisteredService)2 OAuth20Constants (org.apereo.cas.support.oauth.OAuth20Constants)2 OAuth20GrantTypes (org.apereo.cas.support.oauth.OAuth20GrantTypes)2