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;
}
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;
}
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));
}
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;
}
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);
}
Aggregations