Search in sources :

Example 1 with RefreshToken

use of org.apereo.cas.ticket.refreshtoken.RefreshToken in project cas by apereo.

the class OAuth20AccessTokenEndpointController method handleRequestInternal.

/**
     * Handle request internal model and view.
     *
     * @param request  the request
     * @param response the response
     * @return the model and view
     * @throws Exception the exception
     */
@PostMapping(path = OAuthConstants.BASE_OAUTH20_URL + '/' + OAuthConstants.ACCESS_TOKEN_URL)
public ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    try {
        response.setContentType(MediaType.TEXT_PLAIN_VALUE);
        if (!verifyAccessTokenRequest(request, response)) {
            LOGGER.error("Access token request verification fails");
            return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_REQUEST);
        }
        final String grantType = request.getParameter(OAuthConstants.GRANT_TYPE);
        final Service service;
        final Authentication authentication;
        final boolean generateRefreshToken;
        final OAuthRegisteredService registeredService;
        final J2EContext context = WebUtils.getPac4jJ2EContext(request, response);
        final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
        if (isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE) || isGrantType(grantType, OAuth20GrantTypes.REFRESH_TOKEN)) {
            final Optional<UserProfile> profile = manager.get(true);
            final String clientId = profile.get().getId();
            registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
            // we generate a refresh token if requested by the service but not from a refresh token
            generateRefreshToken = registeredService != null && registeredService.isGenerateRefreshToken() && isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE);
            final String parameterName;
            if (isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE)) {
                parameterName = OAuthConstants.CODE;
            } else {
                parameterName = OAuthConstants.REFRESH_TOKEN;
            }
            final OAuthToken token = getToken(request, parameterName);
            if (token == null) {
                LOGGER.error("No token found for authorization_code or refresh_token grant types");
                return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_GRANT);
            }
            service = token.getService();
            authentication = token.getAuthentication();
        } else {
            final String clientId = request.getParameter(OAuthConstants.CLIENT_ID);
            registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
            generateRefreshToken = registeredService != null && registeredService.isGenerateRefreshToken();
            try {
                // resource owner password grant type
                final Optional<OAuthUserProfile> profile = manager.get(true);
                if (!profile.isPresent()) {
                    throw new UnauthorizedServiceException("OAuth user profile cannot be determined");
                }
                service = createService(registeredService, context);
                authentication = createAuthentication(profile.get(), registeredService, context, service);
                RegisteredServiceAccessStrategyUtils.ensurePrincipalAccessIsAllowedForService(service, registeredService, authentication);
            } catch (final Exception e) {
                LOGGER.error(e.getMessage(), e);
                return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_GRANT);
            }
        }
        final AccessToken accessToken = generateAccessToken(service, authentication, context);
        RefreshToken refreshToken = null;
        if (generateRefreshToken) {
            refreshToken = this.refreshTokenFactory.create(service, authentication);
            getTicketRegistry().addTicket(refreshToken);
        }
        LOGGER.debug("access token: [{}] / timeout: [{}] / refresh token: [{}]", accessToken, casProperties.getTicket().getTgt().getTimeToKillInSeconds(), refreshToken);
        final String responseType = context.getRequestParameter(OAuthConstants.RESPONSE_TYPE);
        final OAuth20ResponseTypes type = Arrays.stream(OAuth20ResponseTypes.values()).filter(t -> t.getType().equalsIgnoreCase(responseType)).findFirst().orElse(OAuth20ResponseTypes.CODE);
        this.accessTokenResponseGenerator.generate(request, response, registeredService, service, accessToken, refreshToken, casProperties.getTicket().getTgt().getTimeToKillInSeconds(), type);
        getTicketRegistry().addTicket(accessToken);
        response.setStatus(HttpServletResponse.SC_OK);
        return null;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw Throwables.propagate(e);
    }
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) OAuth20ResponseTypes(org.apereo.cas.support.oauth.OAuth20ResponseTypes) OAuthUserProfile(org.apereo.cas.support.oauth.profile.OAuthUserProfile) UserProfile(org.pac4j.core.profile.UserProfile) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) Service(org.apereo.cas.authentication.principal.Service) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) J2EContext(org.pac4j.core.context.J2EContext) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) OAuthToken(org.apereo.cas.ticket.OAuthToken) RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) Authentication(org.apereo.cas.authentication.Authentication) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) OAuthUserProfile(org.apereo.cas.support.oauth.profile.OAuthUserProfile) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 2 with RefreshToken

use of org.apereo.cas.ticket.refreshtoken.RefreshToken in project cas by apereo.

the class OAuth20AccessTokenControllerTests method internalVerifyRefreshTokenOk.

private void internalVerifyRefreshTokenOk(final RegisteredService service, final boolean json) throws Exception {
    final Principal principal = createPrincipal();
    final RefreshToken refreshToken = addRefreshToken(principal, service);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuth20GrantTypes.REFRESH_TOKEN.name().toLowerCase());
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REFRESH_TOKEN, refreshToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    //This assert fails because deep down inside Oauth2 access token ctrl the refresh token gets deleted
    //assertNotNull(oAuth20AccessTokenController.getRegistry().getTicket((refreshToken.getId())));
    assertEquals(200, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();
    final String accessTokenId;
    if (json) {
        assertEquals("application/json", mockResponse.getContentType());
        assertTrue(body.contains('"' + OAuthConstants.ACCESS_TOKEN + "\":\"AT-"));
        assertFalse(body.contains('"' + OAuthConstants.REFRESH_TOKEN + "\":\"RT-"));
        assertTrue(body.contains('"' + OAuthConstants.EXPIRES_IN + "\":7"));
        accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + "\":\"", "\",\"");
    } else {
        assertEquals("text/plain", mockResponse.getContentType());
        assertTrue(body.contains(OAuthConstants.ACCESS_TOKEN + '='));
        assertFalse(body.contains(OAuthConstants.REFRESH_TOKEN + '='));
        assertTrue(body.contains(OAuthConstants.EXPIRES_IN + '='));
        accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + '=', "&");
    }
    final AccessToken accessToken = oAuth20AccessTokenController.getTicketRegistry().getTicket(accessTokenId, AccessToken.class);
    assertEquals(principal, accessToken.getAuthentication().getPrincipal());
    final int timeLeft = getTimeLeft(body, false, json);
    assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
}
Also used : RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) Principal(org.apereo.cas.authentication.principal.Principal) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 3 with RefreshToken

use of org.apereo.cas.ticket.refreshtoken.RefreshToken in project cas by apereo.

the class OAuth20AccessTokenControllerTests method verifyRefreshTokenBadCredentials.

@Test
public void verifyRefreshTokenBadCredentials() throws Exception {
    final Principal principal = createPrincipal();
    final RegisteredService service = addRegisteredService();
    final RefreshToken refreshToken = addRefreshToken(principal, service);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuth20GrantTypes.REFRESH_TOKEN.name().toLowerCase());
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, WRONG_CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REFRESH_TOKEN, refreshToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertEquals(HttpStatus.SC_UNAUTHORIZED, mockResponse.getStatus());
    assertEquals(ERROR_EQUALS + OAuthConstants.INVALID_REQUEST, mockResponse.getContentAsString());
}
Also used : OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Principal(org.apereo.cas.authentication.principal.Principal) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 4 with RefreshToken

use of org.apereo.cas.ticket.refreshtoken.RefreshToken in project cas by apereo.

the class OAuth20AccessTokenControllerTests method addRefreshToken.

private RefreshToken addRefreshToken(final Principal principal, final RegisteredService registeredService) {
    final Authentication authentication = getAuthentication(principal);
    final WebApplicationServiceFactory factory = new WebApplicationServiceFactory();
    final Service service = factory.createService(registeredService.getServiceId());
    final RefreshToken refreshToken = oAuthRefreshTokenFactory.create(service, authentication);
    oAuth20AccessTokenController.getTicketRegistry().addTicket(refreshToken);
    return refreshToken;
}
Also used : RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) Authentication(org.apereo.cas.authentication.Authentication) WebApplicationServiceFactory(org.apereo.cas.authentication.principal.WebApplicationServiceFactory) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service)

Example 5 with RefreshToken

use of org.apereo.cas.ticket.refreshtoken.RefreshToken in project cas by apereo.

the class OAuth20AccessTokenEndpointController method getToken.

/**
     * Return the OAuth token (a code or a refresh token).
     *
     * @param request       the HTTP request
     * @param parameterName the parameter name
     * @return the OAuth token
     */
private OAuthToken getToken(final HttpServletRequest request, final String parameterName) {
    final String codeParameter = request.getParameter(parameterName);
    final OAuthToken token = getTicketRegistry().getTicket(codeParameter, OAuthToken.class);
    // token should not be expired
    if (token == null || token.isExpired()) {
        LOGGER.error("Code or refresh token expired: [{}]", token);
        if (token != null) {
            getTicketRegistry().deleteTicket(token.getId());
        }
        return null;
    }
    if (token instanceof OAuthCode && !(token instanceof RefreshToken)) {
        getTicketRegistry().deleteTicket(token.getId());
    }
    return token;
}
Also used : OAuthToken(org.apereo.cas.ticket.OAuthToken) RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) OAuthCode(org.apereo.cas.ticket.code.OAuthCode)

Aggregations

RefreshToken (org.apereo.cas.ticket.refreshtoken.RefreshToken)6 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)4 Authentication (org.apereo.cas.authentication.Authentication)3 Principal (org.apereo.cas.authentication.principal.Principal)3 Service (org.apereo.cas.authentication.principal.Service)3 RegisteredService (org.apereo.cas.services.RegisteredService)3 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 WebApplicationServiceFactory (org.apereo.cas.authentication.principal.WebApplicationServiceFactory)2 OAuthToken (org.apereo.cas.ticket.OAuthToken)2 AccessToken (org.apereo.cas.ticket.accesstoken.AccessToken)2 Test (org.junit.Test)2 WebApplicationService (org.apereo.cas.authentication.principal.WebApplicationService)1 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)1 OAuth20ResponseTypes (org.apereo.cas.support.oauth.OAuth20ResponseTypes)1 OAuthUserProfile (org.apereo.cas.support.oauth.profile.OAuthUserProfile)1 OAuthCode (org.apereo.cas.ticket.code.OAuthCode)1 DefaultRefreshTokenFactory (org.apereo.cas.ticket.refreshtoken.DefaultRefreshTokenFactory)1 AlwaysExpiresExpirationPolicy (org.apereo.cas.ticket.support.AlwaysExpiresExpirationPolicy)1 J2EContext (org.pac4j.core.context.J2EContext)1