Search in sources :

Example 1 with OAuth20AccessToken

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));
}
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) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 2 with OAuth20AccessToken

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));
}
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 3 with OAuth20AccessToken

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;
}
Also used : lombok.val(lombok.val) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken) BasicAuthExtractor(org.pac4j.core.credentials.extractor.BasicAuthExtractor) ResponseEntity(org.springframework.http.ResponseEntity) OAuth20IntrospectionAccessTokenResponse(org.apereo.cas.support.oauth.web.response.introspection.OAuth20IntrospectionAccessTokenResponse) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) JEEContext(org.pac4j.core.context.JEEContext) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) UsernamePasswordCredentials(org.pac4j.core.credentials.UsernamePasswordCredentials) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 4 with OAuth20AccessToken

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;
}
Also used : lombok.val(lombok.val) LinkedHashMap(java.util.LinkedHashMap) OAuthCoreProperties(org.apereo.cas.configuration.model.support.oauth.OAuthCoreProperties) HttpStatus(org.springframework.http.HttpStatus) Slf4j(lombok.extern.slf4j.Slf4j) OAuth20Utils(org.apereo.cas.support.oauth.util.OAuth20Utils) Map(java.util.Map) RequiredArgsConstructor(lombok.RequiredArgsConstructor) lombok.val(lombok.val) HttpServletResponse(javax.servlet.http.HttpServletResponse) ResponseEntity(org.springframework.http.ResponseEntity) OAuthProperties(org.apereo.cas.configuration.model.support.oauth.OAuthProperties) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken) LinkedHashMap(java.util.LinkedHashMap)

Example 5 with OAuth20AccessToken

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();
}
Also used : lombok.val(lombok.val) OAuth20AccessToken(org.apereo.cas.ticket.accesstoken.OAuth20AccessToken) ModelAndView(org.springframework.web.servlet.ModelAndView)

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