Search in sources :

Example 16 with SavedRequest

use of org.springframework.security.web.savedrequest.SavedRequest in project gocd by gocd.

the class SessionUtils method redirectToLoginPage.

public static void redirectToLoginPage(HttpServletRequest request, HttpServletResponse response, String errorMessage) throws IOException {
    SavedRequest savedRequest = SessionUtils.savedRequest(request);
    SessionUtils.recreateSessionWithoutCopyingOverSessionState(request);
    SessionUtils.saveRequest(request, savedRequest);
    SessionUtils.setAuthenticationError(errorMessage, request);
    response.sendRedirect("/go/auth/login");
}
Also used : SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) DefaultSavedRequest(org.springframework.security.web.savedrequest.DefaultSavedRequest)

Example 17 with SavedRequest

use of org.springframework.security.web.savedrequest.SavedRequest in project flow by vaadin.

the class VaadinDefaultRequestCacheTest method getRequest_uses_delegateRequestCache.

@Test
public void getRequest_uses_delegateRequestCache() throws Exception {
    HttpServletRequest request = RequestUtilTest.createRequest("/hello-world", null);
    HttpServletResponse response = createResponse();
    SavedRequest expectedSavedRequest = Mockito.mock(SavedRequest.class);
    RequestCache delegateRequestCache = Mockito.mock(RequestCache.class);
    Mockito.doReturn(expectedSavedRequest).when(delegateRequestCache).getRequest(request, response);
    cache.setDelegateRequestCache(delegateRequestCache);
    SavedRequest actualSavedRequest = cache.getRequest(request, response);
    Mockito.verify(delegateRequestCache).getRequest(request, response);
    Assert.assertEquals(expectedSavedRequest, actualSavedRequest);
    cache.setDelegateRequestCache(new HttpSessionRequestCache());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) RequestCache(org.springframework.security.web.savedrequest.RequestCache) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) HttpServletResponse(javax.servlet.http.HttpServletResponse) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 18 with SavedRequest

use of org.springframework.security.web.savedrequest.SavedRequest in project flow by vaadin.

the class VaadinSavedRequestAwareAuthenticationSuccessHandler method onAuthenticationSuccess.

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
    SavedRequest savedRequest = this.requestCache.getRequest(request, response);
    String storedServerNavigation = getStoredServerNavigation(request);
    if (storedServerNavigation != null) {
        // The saved server navigation URL is relative to the context path
        if (!"".equals(request.getContextPath())) {
            storedServerNavigation = "/" + storedServerNavigation;
        }
        response.setHeader(SAVED_URL_HEADER, storedServerNavigation);
    } else if (savedRequest != null) {
        /*
             * This is here instead of in sendRedirect as we do not want to
             * fallback to the default URL but instead send that separately.
             */
        response.setHeader(SAVED_URL_HEADER, savedRequest.getRedirectUrl());
    }
    if (isTypescriptLogin(request)) {
        response.setHeader(DEFAULT_URL_HEADER, determineTargetUrl(request, response));
    }
    super.onAuthenticationSuccess(request, response, authentication);
}
Also used : SavedRequest(org.springframework.security.web.savedrequest.SavedRequest)

Example 19 with SavedRequest

use of org.springframework.security.web.savedrequest.SavedRequest in project ORCID-Source by ORCID.

the class OauthRegistrationController method checkRegisterForm.

@RequestMapping(value = "/oauth/custom/register.json", method = RequestMethod.POST)
@ResponseBody
public OauthRegistrationForm checkRegisterForm(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthRegistrationForm form) {
    form.setErrors(new ArrayList<String>());
    RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
    if (form.getApproved()) {
        registrationController.validateRegistrationFields(request, form);
        registrationController.validateGrcaptcha(request, form);
    } else {
        SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
        String stateParam = null;
        if (savedRequest != null && savedRequest.getParameterMap() != null && savedRequest.getParameterValues("state") != null) {
            if (savedRequest.getParameterValues("state").length > 0)
                stateParam = savedRequest.getParameterValues("state")[0];
        }
        form.setRedirectUrl(buildDenyRedirectUri(requestInfoForm.getRedirectUrl(), stateParam));
    }
    return form;
}
Also used : HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 20 with SavedRequest

use of org.springframework.security.web.savedrequest.SavedRequest in project ORCID-Source by ORCID.

the class OauthRegistrationController method registerAndAuthorize.

@RequestMapping(value = "/oauth/custom/registerConfirm.json", method = RequestMethod.POST)
@ResponseBody
public RequestInfoForm registerAndAuthorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthRegistrationForm form) {
    RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
    if (form.getApproved()) {
        boolean usedCaptcha = false;
        // block google.
        if (form.getGrecaptchaWidgetId().getValue() != null) {
            // to the login page
            if (request.getSession().getAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME) == null || PojoUtil.isEmpty(form.getGrecaptcha()) || !form.getGrecaptcha().getValue().equals(request.getSession().getAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME))) {
                String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
                // Set the client id
                redirectUri = redirectUri.replace("{0}", requestInfoForm.getClientId());
                // Set the response type if needed
                if (!PojoUtil.isEmpty(requestInfoForm.getResponseType()))
                    redirectUri += "&response_type=" + requestInfoForm.getResponseType();
                // Set the redirect uri
                if (!PojoUtil.isEmpty(requestInfoForm.getRedirectUrl()))
                    redirectUri += "&redirect_uri=" + requestInfoForm.getRedirectUrl();
                // remove email access scope if present but not granted
                if (requestInfoForm.containsEmailReadPrivateScope() && !form.isEmailAccessAllowed()) {
                    requestInfoForm.removeEmailReadPrivateScope();
                }
                // Set the scope param
                if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()))
                    redirectUri += "&scope=" + requestInfoForm.getScopesAsString();
                // Copy the state param if present
                if (!PojoUtil.isEmpty(requestInfoForm.getStateParam()))
                    redirectUri += "&state=" + requestInfoForm.getStateParam();
                requestInfoForm.setRedirectUrl(redirectUri);
                SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
                if (savedRequest != null)
                    LOGGER.info("OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl());
                LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: " + requestInfoForm.getRedirectUrl());
                return requestInfoForm;
            }
            usedCaptcha = true;
        }
        // Remove the session hash if needed
        if (request.getSession().getAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME) != null) {
            request.getSession().removeAttribute(RegistrationController.GRECAPTCHA_SESSION_ATTRIBUTE_NAME);
        }
        // Strip any html code from names before validating them
        if (!PojoUtil.isEmpty(form.getFamilyNames())) {
            form.getFamilyNames().setValue(OrcidStringUtils.stripHtml(form.getFamilyNames().getValue()));
        }
        if (!PojoUtil.isEmpty(form.getGivenNames())) {
            form.getGivenNames().setValue(OrcidStringUtils.stripHtml(form.getGivenNames().getValue()));
        }
        // Check there are no errors
        registrationController.validateRegistrationFields(request, form);
        if (form.getErrors().isEmpty()) {
            // Register user
            try {
                // Locale
                Locale locale = RequestContextUtils.getLocale(request);
                // Ip
                String ip = OrcidRequestUtil.getIpAddress(request);
                registrationController.createMinimalRegistration(request, form, usedCaptcha, locale, ip);
            } catch (Exception e) {
                requestInfoForm.getErrors().add(getMessage("register.error.generalError"));
                return requestInfoForm;
            }
            // Authenticate user
            String email = form.getEmail().getValue();
            String password = form.getPassword().getValue();
            Authentication auth = authenticateUser(request, email, password);
            // Create authorization params
            SimpleSessionStatus status = new SimpleSessionStatus();
            Map<String, Object> model = new HashMap<String, Object>();
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String> approvalParams = new HashMap<String, String>();
            fillOauthParams(requestInfoForm, params, approvalParams, form.getPersistentTokenEnabled(), form.isEmailAccessAllowed());
            // Authorize
            try {
                authorizationEndpoint.authorize(model, params, status, auth);
            } catch (RedirectMismatchException rUriError) {
                String redirectUri = this.getBaseUri() + REDIRECT_URI_ERROR;
                // Set the client id
                redirectUri = redirectUri.replace("{0}", requestInfoForm.getClientId());
                // Set the response type if needed
                if (!PojoUtil.isEmpty(requestInfoForm.getResponseType()))
                    redirectUri += "&response_type=" + requestInfoForm.getResponseType();
                // Set the redirect uri
                if (!PojoUtil.isEmpty(requestInfoForm.getRedirectUrl()))
                    redirectUri += "&redirect_uri=" + requestInfoForm.getRedirectUrl();
                // Set the scope param
                if (!PojoUtil.isEmpty(requestInfoForm.getScopesAsString()))
                    redirectUri += "&scope=" + requestInfoForm.getScopesAsString();
                // Copy the state param if present
                if (!PojoUtil.isEmpty(requestInfoForm.getStateParam()))
                    redirectUri += "&state=" + requestInfoForm.getStateParam();
                requestInfoForm.setRedirectUrl(redirectUri);
                LOGGER.info("OauthRegisterController being sent to client browser: " + requestInfoForm.getRedirectUrl());
                return requestInfoForm;
            }
            Boolean isOauth2ScreensRequest = (Boolean) request.getSession().getAttribute(OrcidOauth2Constants.OAUTH_2SCREENS);
            if (isOauth2ScreensRequest != null && isOauth2ScreensRequest) {
                // Just redirect to the authorization screen
                String queryString = (String) request.getSession().getAttribute(OrcidOauth2Constants.OAUTH_QUERY_STRING);
                requestInfoForm.setRedirectUrl(orcidUrlManager.getBaseUrl() + "/oauth/authorize?" + queryString);
                request.getSession().removeAttribute(OrcidOauth2Constants.OAUTH_2SCREENS);
            } else {
                // Approve
                RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
                requestInfoForm.setRedirectUrl(view.getUrl());
            }
        }
    } else {
        requestInfoForm.setRedirectUrl(buildDenyRedirectUri(requestInfoForm.getRedirectUrl(), requestInfoForm.getStateParam()));
    }
    if (new HttpSessionRequestCache().getRequest(request, response) != null)
        new HttpSessionRequestCache().removeRequest(request, response);
    LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: " + requestInfoForm.getRedirectUrl());
    return requestInfoForm;
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) Authentication(org.springframework.security.core.Authentication) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) RedirectView(org.springframework.web.servlet.view.RedirectView) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) SimpleSessionStatus(org.springframework.web.bind.support.SimpleSessionStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

SavedRequest (org.springframework.security.web.savedrequest.SavedRequest)27 HttpSessionRequestCache (org.springframework.security.web.savedrequest.HttpSessionRequestCache)8 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 HttpSession (javax.servlet.http.HttpSession)4 Test (org.junit.jupiter.api.Test)4 Authentication (org.springframework.security.core.Authentication)4 Test (org.junit.Test)3 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 DefaultSavedRequest (org.springframework.security.web.savedrequest.DefaultSavedRequest)3 RedirectView (org.springframework.web.servlet.view.RedirectView)3 MidpointAuthentication (com.evolveum.midpoint.authentication.api.config.MidpointAuthentication)2 MockHttpServletRequest (com.thoughtworks.go.http.mocks.MockHttpServletRequest)2 MockHttpServletResponse (com.thoughtworks.go.http.mocks.MockHttpServletResponse)2 RequestInfoForm (org.orcid.pojo.ajaxForm.RequestInfoForm)2 AuthenticationException (org.springframework.security.core.AuthenticationException)2 RequestCache (org.springframework.security.web.savedrequest.RequestCache)2 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)2 ModuleAuthentication (com.evolveum.midpoint.authentication.api.config.ModuleAuthentication)1 ModuleAuthenticationImpl (com.evolveum.midpoint.authentication.impl.module.authentication.ModuleAuthenticationImpl)1