use of org.apereo.cas.ticket.accesstoken.OAuth20AccessToken in project cas by apereo.
the class OAuth20AuthorizeEndpointControllerTests method verifyTokenRedirectToClient.
@Test
public void verifyTokenRedirectToClient() 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);
mockRequest.setContextPath(StringUtils.EMPTY);
val mockResponse = new MockHttpServletResponse();
val oauthContext = oAuth20AuthorizeEndpointController.getConfigurationContext();
oauthContext.getCasProperties().getSessionReplication().getCookie().setAutoConfigureCookiePath(false);
oauthContext.getOauthDistributedSessionCookieGenerator().setCookiePath(StringUtils.EMPTY);
val service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
service.setBypassApprovalPrompt(true);
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 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));
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="));
assertEquals(StringUtils.EMPTY, oAuth20AuthorizeEndpointController.getConfigurationContext().getOauthDistributedSessionCookieGenerator().getCookiePath());
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));
val expiresIn = StringUtils.substringAfter(redirectUrl, "&expires_in=");
assertEquals(getDefaultAccessTokenExpiration(), Long.parseLong(expiresIn));
}
use of org.apereo.cas.ticket.accesstoken.OAuth20AccessToken in project cas by apereo.
the class OAuth20AuthorizeEndpointControllerTests method verifyTokenRedirectToClientWithState.
@Test
public void verifyTokenRedirectToClientWithState() 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);
mockRequest.setParameter(OAuth20Constants.STATE, STATE);
val mockResponse = new MockHttpServletResponse();
val service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
service.setBypassApprovalPrompt(true);
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));
val modelAndView = oAuth20AuthorizeEndpointController.handleRequest(mockRequest, mockResponse);
val view = modelAndView.getView();
assertTrue(view instanceof RedirectView);
val redirectView = (RedirectView) view;
var redirectUrl = redirectView.getUrl();
assertNotNull(redirectUrl);
redirectUrl += "&";
assertTrue(redirectUrl.startsWith(REDIRECT_URI + "#access_token="));
val code = StringUtils.substringBetween(redirectUrl, "#access_token=", "&");
val state = StringUtils.substringBetween(redirectUrl, "state=", "&");
val accessToken = (OAuth20AccessToken) this.ticketRegistry.getTicket(code);
assertNotNull(accessToken);
assertEquals(state, OAuth20Constants.STATE);
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 OAuth20IntrospectionEndpointController method handlePostRequest.
/**
* Handle post request.
*
* @param request the request
* @param response the response
* @return the response entity
*/
@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, value = '/' + OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.INTROSPECTION_URL)
public ResponseEntity<OAuth20IntrospectionAccessTokenResponse> handlePostRequest(final HttpServletRequest request, final HttpServletResponse response) {
ResponseEntity<OAuth20IntrospectionAccessTokenResponse> result;
try {
val authExtractor = new BasicAuthExtractor();
val context = new JEEContext(request, response);
val credentialsResult = authExtractor.extract(context, getConfigurationContext().getSessionStore());
if (credentialsResult.isEmpty()) {
LOGGER.warn("Unable to locate and extract credentials from the request");
return buildUnauthorizedResponseEntity(OAuth20Constants.INVALID_CLIENT, true);
}
val credentials = (UsernamePasswordCredentials) credentialsResult.get();
val service = OAuth20Utils.getRegisteredOAuthServiceByClientId(getConfigurationContext().getServicesManager(), credentials.getUsername());
if (service == null) {
LOGGER.warn("Unable to locate service definition by client id [{}]", credentials.getUsername());
return buildUnauthorizedResponseEntity(OAuth20Constants.INVALID_CLIENT, true);
}
val validationError = validateIntrospectionRequest(service, credentials, request);
if (validationError.isPresent()) {
result = validationError.get();
} else {
val accessToken = StringUtils.defaultIfBlank(request.getParameter(OAuth20Constants.TOKEN), request.getParameter(OAuth20Constants.ACCESS_TOKEN));
LOGGER.debug("Located access token [{}] in the request", accessToken);
var ticket = (OAuth20AccessToken) null;
try {
val token = extractAccessTokenFrom(accessToken);
ticket = getConfigurationContext().getCentralAuthenticationService().getTicket(token, OAuth20AccessToken.class);
} catch (final InvalidTicketException e) {
LOGGER.trace(e.getMessage(), e);
LOGGER.info("Unable to fetch access token [{}]: [{}]", accessToken, e.getMessage());
}
val introspect = createIntrospectionValidResponse(ticket);
result = new ResponseEntity<>(introspect, HttpStatus.OK);
}
} catch (final Exception e) {
LoggingUtils.error(LOGGER, e);
result = new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
return result;
}
use of org.apereo.cas.ticket.accesstoken.OAuth20AccessToken in project cas by apereo.
the class OAuth20DefaultUserProfileViewRenderer method getRenderedUserProfile.
/**
* Gets rendered user profile.
*
* @param model the model
* @param accessToken the access token
* @param response the response
* @return the rendered user profile
*/
protected Map<String, Object> getRenderedUserProfile(final Map<String, Object> model, final OAuth20AccessToken accessToken, final HttpServletResponse response) {
if (oauthProperties.getCore().getUserProfileViewType() == OAuthCoreProperties.UserProfileViewTypes.FLAT) {
val flattened = new LinkedHashMap<String, Object>();
if (model.containsKey(MODEL_ATTRIBUTE_ATTRIBUTES)) {
val attributes = Map.class.cast(model.get(MODEL_ATTRIBUTE_ATTRIBUTES));
flattened.putAll(attributes);
}
model.keySet().stream().filter(k -> !k.equalsIgnoreCase(MODEL_ATTRIBUTE_ATTRIBUTES)).forEach(k -> flattened.put(k, model.get(k)));
LOGGER.trace("Flattened user profile attributes with the final model as [{}]", model);
return flattened;
}
return model;
}
use of org.apereo.cas.ticket.accesstoken.OAuth20AccessToken in project cas by apereo.
the class OAuth20ResourceOwnerCredentialsResponseBuilder method build.
@Override
public ModelAndView build(final AccessTokenRequestContext holder) throws Exception {
val accessTokenResult = configurationContext.getAccessTokenGenerator().generate(holder);
val result = OAuth20AccessTokenResponseResult.builder().registeredService(holder.getRegisteredService()).service(holder.getService()).accessTokenTimeout(accessTokenResult.getAccessToken().map(OAuth20AccessToken::getExpiresIn).orElse(0L)).responseType(holder.getResponseType()).casProperties(configurationContext.getCasProperties()).generatedToken(accessTokenResult).grantType(holder.getGrantType()).userProfile(holder.getUserProfile()).build();
configurationContext.getAccessTokenResponseGenerator().generate(result);
return new ModelAndView();
}
Aggregations