Search in sources :

Example 6 with AccessToken

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

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

the class OAuth20AccessTokenControllerTests method internalVerifyClientOK.

private void internalVerifyClientOK(final RegisteredService service, final boolean basicAuth, final boolean refreshToken, final boolean json) throws Exception {
    final Principal principal = createPrincipal();
    final OAuthCode code = addCode(principal, service);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuth20GrantTypes.AUTHORIZATION_CODE.name().toLowerCase());
    if (basicAuth) {
        final String auth = CLIENT_ID + ':' + CLIENT_SECRET;
        final String value = Base64.encodeBase64String(auth.getBytes(StandardCharsets.UTF_8));
        mockRequest.addHeader(HttpConstants.AUTHORIZATION_HEADER, HttpConstants.BASIC_HEADER_PREFIX + value);
    } else {
        mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
        mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    }
    mockRequest.setParameter(OAuthConstants.CODE, code.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    assertNull(oAuth20AccessTokenController.getTicketRegistry().getTicket(code.getId()));
    assertEquals(HttpStatus.SC_OK, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();
    final String accessTokenId;
    if (json) {
        assertEquals(MediaType.APPLICATION_JSON_VALUE, mockResponse.getContentType());
        assertTrue(body.contains('"' + OAuthConstants.ACCESS_TOKEN + "\":\"AT-"));
        if (refreshToken) {
            assertTrue(body.contains('"' + OAuthConstants.REFRESH_TOKEN + "\":\"RT-"));
        }
        assertTrue(body.contains('"' + OAuthConstants.EXPIRES_IN + "\":7"));
        accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + "\":\"", "\",\"");
    } else {
        assertEquals(MediaType.TEXT_PLAIN_VALUE, mockResponse.getContentType());
        assertTrue(body.contains(OAuthConstants.ACCESS_TOKEN + "=AT-"));
        if (refreshToken) {
            assertTrue(body.contains(OAuthConstants.REFRESH_TOKEN + "=RT-"));
        }
        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, refreshToken, json);
    assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) OAuthCode(org.apereo.cas.ticket.code.OAuthCode) Principal(org.apereo.cas.authentication.principal.Principal) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 8 with AccessToken

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

the class OAuth20AccessTokenControllerTests method internalVerifyUserAuth.

private void internalVerifyUserAuth(final boolean refreshToken, final boolean json) throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuth20GrantTypes.PASSWORD.name().toLowerCase());
    mockRequest.setParameter(USERNAME, GOOD_USERNAME);
    mockRequest.setParameter(PASSWORD, GOOD_PASSWORD);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    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-"));
        if (refreshToken) {
            assertTrue(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 + '='));
        if (refreshToken) {
            assertTrue(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(GOOD_USERNAME, accessToken.getAuthentication().getPrincipal().getId());
    final int timeLeft = getTimeLeft(body, refreshToken, json);
    assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Example 9 with AccessToken

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

the class OidcAuthorizeEndpointController method buildCallbackUrlForImplicitTokenResponseType.

private String buildCallbackUrlForImplicitTokenResponseType(final J2EContext context, final Authentication authentication, final Service service, final String redirectUri, final String clientId, final OAuth20ResponseTypes responseType) {
    try {
        final AccessToken accessToken = generateAccessToken(service, authentication, context);
        LOGGER.debug("Generated OAuth access token: [{}]", accessToken);
        final OidcRegisteredService oidcService = (OidcRegisteredService) OAuthUtils.getRegisteredOAuthService(this.getServicesManager(), clientId);
        final long timeout = casProperties.getTicket().getTgt().getTimeToKillInSeconds();
        final String idToken = this.idTokenGenerator.generate(context.getRequest(), context.getResponse(), accessToken, timeout, responseType, oidcService);
        LOGGER.debug("Generated id token [{}]", idToken);
        final List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair(OidcConstants.ID_TOKEN, idToken));
        return buildCallbackUrlResponseType(authentication, service, redirectUri, accessToken, params);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList)

Example 10 with AccessToken

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

the class OAuth20AuthorizeControllerTests method verifyTokenRedirectToClient.

@Test
public void verifyTokenRedirectToClient() throws Exception {
    clearAllServices();
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuthConstants.AUTHORIZE_URL);
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.REDIRECT_URI, REDIRECT_URI);
    mockRequest.setParameter(OAuthConstants.RESPONSE_TYPE, OAuth20ResponseTypes.TOKEN.name().toLowerCase());
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
    service.setBypassApprovalPrompt(true);
    oAuth20AuthorizeEndpointController.getServicesManager().save(service);
    final CasProfile profile = new CasProfile();
    profile.setId(ID);
    final Map<String, Object> attributes = new HashMap<>();
    attributes.put(FIRST_NAME_ATTRIBUTE, FIRST_NAME);
    attributes.put(LAST_NAME_ATTRIBUTE, LAST_NAME);
    profile.addAttributes(attributes);
    final MockHttpSession session = new MockHttpSession();
    mockRequest.setSession(session);
    session.putValue(Pac4jConstants.USER_PROFILES, profile);
    final ModelAndView modelAndView = oAuth20AuthorizeEndpointController.handleRequestInternal(mockRequest, mockResponse);
    final View view = modelAndView.getView();
    assertTrue(view instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) view;
    final String redirectUrl = redirectView.getUrl();
    assertTrue(redirectUrl.startsWith(REDIRECT_URI + "#access_token="));
    final String code = StringUtils.substringBetween(redirectUrl, "#access_token=", "&token_type=bearer");
    final AccessToken accessToken = (AccessToken) oAuth20AuthorizeEndpointController.getTicketRegistry().getTicket(code);
    assertNotNull(accessToken);
    final Principal principal = accessToken.getAuthentication().getPrincipal();
    assertEquals(ID, principal.getId());
    final Map<String, Object> principalAttributes = principal.getAttributes();
    assertEquals(attributes.size(), principalAttributes.size());
    assertEquals(FIRST_NAME, principalAttributes.get(FIRST_NAME_ATTRIBUTE));
}
Also used : CasProfile(org.pac4j.cas.profile.CasProfile) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) RedirectView(org.springframework.web.servlet.view.RedirectView) MockHttpSession(org.springframework.mock.web.MockHttpSession) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Principal(org.apereo.cas.authentication.principal.Principal) Test(org.junit.Test)

Aggregations

AccessToken (org.apereo.cas.ticket.accesstoken.AccessToken)12 Principal (org.apereo.cas.authentication.principal.Principal)6 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)6 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)6 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)5 HashMap (java.util.HashMap)3 Test (org.junit.Test)3 CasProfile (org.pac4j.cas.profile.CasProfile)3 Authentication (org.apereo.cas.authentication.Authentication)2 OidcRegisteredService (org.apereo.cas.services.OidcRegisteredService)2 OAuth20ResponseTypes (org.apereo.cas.support.oauth.OAuth20ResponseTypes)2 RefreshToken (org.apereo.cas.ticket.refreshtoken.RefreshToken)2 J2EContext (org.pac4j.core.context.J2EContext)2 ProfileManager (org.pac4j.core.profile.ProfileManager)2 UserProfile (org.pac4j.core.profile.UserProfile)2 MockHttpSession (org.springframework.mock.web.MockHttpSession)2 ModelAndView (org.springframework.web.servlet.ModelAndView)2 View (org.springframework.web.servlet.View)2 RedirectView (org.springframework.web.servlet.view.RedirectView)2 ArrayList (java.util.ArrayList)1