Search in sources :

Example 36 with RedirectView

use of org.springframework.web.servlet.view.RedirectView in project cas by apereo.

the class OAuth20TokenAuthorizationResponseBuilder method buildCallbackUrlResponseType.

/**
 * Build callback url response type string.
 *
 * @param holder       the holder
 * @param redirectUri  the redirect uri
 * @param accessToken  the access token
 * @param params       the params
 * @param refreshToken the refresh token
 * @param context      the context
 * @return the string
 * @throws Exception the exception
 */
protected View buildCallbackUrlResponseType(final AccessTokenRequestDataHolder holder, final String redirectUri, final AccessToken accessToken, final List<NameValuePair> params, final RefreshToken refreshToken, final J2EContext context) throws Exception {
    final String state = holder.getAuthentication().getAttributes().get(OAuth20Constants.STATE).toString();
    final String nonce = holder.getAuthentication().getAttributes().get(OAuth20Constants.NONCE).toString();
    final URIBuilder builder = new URIBuilder(redirectUri);
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(OAuth20Constants.ACCESS_TOKEN).append('=').append(accessToken.getId()).append('&').append(OAuth20Constants.TOKEN_TYPE).append('=').append(OAuth20Constants.TOKEN_TYPE_BEARER).append('&').append(OAuth20Constants.EXPIRES_IN).append('=').append(accessTokenExpirationPolicy.getTimeToLive());
    if (refreshToken != null) {
        stringBuilder.append('&').append(OAuth20Constants.REFRESH_TOKEN).append('=').append(refreshToken.getId());
    }
    params.forEach(p -> stringBuilder.append('&').append(p.getName()).append('=').append(p.getValue()));
    if (StringUtils.isNotBlank(state)) {
        stringBuilder.append('&').append(OAuth20Constants.STATE).append('=').append(EncodingUtils.urlEncode(state));
    }
    if (StringUtils.isNotBlank(nonce)) {
        stringBuilder.append('&').append(OAuth20Constants.NONCE).append('=').append(EncodingUtils.urlEncode(nonce));
    }
    builder.setFragment(stringBuilder.toString());
    final String url = builder.toString();
    LOGGER.debug("Redirecting to URL [{}]", url);
    return new RedirectView(url);
}
Also used : RedirectView(org.springframework.web.servlet.view.RedirectView) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 37 with RedirectView

use of org.springframework.web.servlet.view.RedirectView in project cas by apereo.

the class OAuth20AuthorizeControllerTests method verifyTokenRedirectToClientWithState.

@Test
public void verifyTokenRedirectToClientWithState() throws Exception {
    clearAllServices();
    final MockHttpServletRequest 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);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
    service.setBypassApprovalPrompt(true);
    this.servicesManager.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.handleRequest(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="));
    assertTrue(redirectUrl.contains('&' + OAuth20Constants.STATE + '=' + STATE));
    final String code = StringUtils.substringBetween(redirectUrl, "#access_token=", "&token_type=bearer");
    final AccessToken accessToken = (AccessToken) this.ticketRegistry.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)

Example 38 with RedirectView

use of org.springframework.web.servlet.view.RedirectView in project cas by apereo.

the class OAuth20AuthorizeControllerTests method verifyCodeRedirectToClientApproved.

@Test
public void verifyCodeRedirectToClientApproved() throws Exception {
    clearAllServices();
    final MockHttpServletRequest 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.CODE.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(false);
    this.servicesManager.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(OAuth20Constants.BYPASS_APPROVAL_PROMPT, "true");
    session.putValue(Pac4jConstants.USER_PROFILES, profile);
    final ModelAndView modelAndView = oAuth20AuthorizeEndpointController.handleRequest(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 + "?code=OC-"));
    final String code = StringUtils.substringAfter(redirectUrl, "?code=");
    final OAuthCode oAuthCode = (OAuthCode) this.ticketRegistry.getTicket(code);
    assertNotNull(oAuthCode);
    final Principal principal = oAuthCode.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) OAuthCode(org.apereo.cas.ticket.code.OAuthCode) RedirectView(org.springframework.web.servlet.view.RedirectView) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View) 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)

Example 39 with RedirectView

use of org.springframework.web.servlet.view.RedirectView in project cas by apereo.

the class OAuth20AuthorizeControllerTests method verifyCodeRedirectToClientWithState.

@Test
public void verifyCodeRedirectToClientWithState() throws Exception {
    clearAllServices();
    final MockHttpServletRequest 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.CODE.name().toLowerCase());
    mockRequest.setServerName(CAS_SERVER);
    mockRequest.setServerPort(CAS_PORT);
    mockRequest.setScheme(CAS_SCHEME);
    mockRequest.setParameter(OAuth20Constants.STATE, STATE);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuthRegisteredService service = getRegisteredService(REDIRECT_URI, SERVICE_NAME);
    service.setBypassApprovalPrompt(true);
    this.servicesManager.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.handleRequest(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 + "?code=OC-"));
    final String code = StringUtils.substringBefore(StringUtils.substringAfter(redirectUrl, "?code="), "&state=");
    final OAuthCode oAuthCode = (OAuthCode) this.ticketRegistry.getTicket(code);
    assertNotNull(oAuthCode);
    final Principal principal = oAuthCode.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) OAuthCode(org.apereo.cas.ticket.code.OAuthCode) RedirectView(org.springframework.web.servlet.view.RedirectView) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View) 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)

Example 40 with RedirectView

use of org.springframework.web.servlet.view.RedirectView in project cas by apereo.

the class WsFederationNavigationController method redirectToProvider.

/**
 * Redirect to provider. Receive the client name from the request and then try to determine and build the endpoint url
 * for the redirection. The redirection data/url must contain a delegated client ticket id so that the request be can
 * restored on the trip back. SAML clients use the relay-state session attribute while others use request parameters.
 *
 * @param request  the request
 * @param response the response
 * @return the view
 */
@GetMapping(ENDPOINT_REDIRECT)
public View redirectToProvider(final HttpServletRequest request, final HttpServletResponse response) {
    final String wsfedId = request.getParameter(PARAMETER_NAME);
    try {
        final WsFederationConfiguration cfg = configurations.stream().filter(c -> c.getId().equals(wsfedId)).findFirst().orElse(null);
        if (cfg == null) {
            throw new IllegalArgumentException("Could not locate WsFederation configuration for " + wsfedId);
        }
        final Service service = determineService(request);
        final String id = wsFederationHelper.getRelyingPartyIdentifier(service, cfg);
        final String url = cfg.getAuthorizationUrl(id, cfg.getId());
        wsFederationCookieManager.store(request, response, cfg.getId(), service, cfg);
        return new RedirectView(url);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, StringUtils.EMPTY);
}
Also used : RedirectView(org.springframework.web.servlet.view.RedirectView) WsFederationConfiguration(org.apereo.cas.support.wsfederation.WsFederationConfiguration) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) Service(org.apereo.cas.authentication.principal.Service) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

RedirectView (org.springframework.web.servlet.view.RedirectView)86 ModelAndView (org.springframework.web.servlet.ModelAndView)70 Test (org.junit.Test)34 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)19 HashMap (java.util.HashMap)18 View (org.springframework.web.servlet.View)17 Authentication (org.springframework.security.core.Authentication)14 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)13 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)8 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)8 DefaultUserApprovalHandler (org.springframework.security.oauth2.provider.approval.DefaultUserApprovalHandler)8 ServletException (javax.servlet.ServletException)7 RequestInfoForm (org.orcid.pojo.ajaxForm.RequestInfoForm)7 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)7 TokenGranter (org.springframework.security.oauth2.provider.TokenGranter)7 Principal (org.apereo.cas.authentication.principal.Principal)6 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)6 CasProfile (org.pac4j.cas.profile.CasProfile)6 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)6