Search in sources :

Example 1 with HttpSessionRequestCache

use of org.springframework.security.web.savedrequest.HttpSessionRequestCache in project spring-security by spring-projects.

the class RequestCacheConfigurer method getRequestCache.

/**
	 * Gets the {@link RequestCache} to use. If one is defined using
	 * {@link #requestCache(org.springframework.security.web.savedrequest.RequestCache)},
	 * then it is used. Otherwise, an attempt to find a {@link RequestCache} shared object
	 * is made. If that fails, an {@link HttpSessionRequestCache} is used
	 *
	 * @param http the {@link HttpSecurity} to attempt to fined the shared object
	 * @return the {@link RequestCache} to use
	 */
private RequestCache getRequestCache(H http) {
    RequestCache result = http.getSharedObject(RequestCache.class);
    if (result != null) {
        return result;
    }
    HttpSessionRequestCache defaultCache = new HttpSessionRequestCache();
    defaultCache.setRequestMatcher(createDefaultSavedRequestMatcher(http));
    return defaultCache;
}
Also used : RequestCache(org.springframework.security.web.savedrequest.RequestCache) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache)

Example 2 with HttpSessionRequestCache

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

the class LocaleChangeInterceptor method preHandle.

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException {
    String newLocale = request.getParameter(this.paramName);
    if (newLocale == null) {
        SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
        if (savedRequest != null) {
            String url = savedRequest.getRedirectUrl();
            Matcher matcher = langPattern.matcher(url);
            if (matcher.find()) {
                newLocale = matcher.group(2);
            }
        }
    }
    if (newLocale != null) {
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if (localeResolver == null) {
            throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request?");
        }
        try {
            localeResolver.setLocale(request, response, StringUtils.parseLocaleString(newLocale));
        } catch (Exception e) {
        /* 
                             * Ignore exceptions from invalid locales as it will cause a 500 error and
                             * continue with the last valid locale set.
                             */
        }
    }
    // Proceed in any case.
    return true;
}
Also used : LocaleResolver(org.springframework.web.servlet.LocaleResolver) Matcher(java.util.regex.Matcher) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) ServletException(javax.servlet.ServletException) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest)

Example 3 with HttpSessionRequestCache

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

the class OauthLoginController method authenticateAndAuthorize.

@RequestMapping(value = { "/oauth/custom/signin.json", "/oauth/custom/login.json" }, method = RequestMethod.POST)
@ResponseBody
public OauthAuthorizeForm authenticateAndAuthorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
    // Clean form errors
    form.setErrors(new ArrayList<String>());
    RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
    boolean willBeRedirected = false;
    if (form.getApproved()) {
        // Validate name and password
        validateUserNameAndPassword(form);
        if (form.getErrors().isEmpty()) {
            try {
                // Authenticate user
                Authentication auth = authenticateUser(request, form.getUserName().getValue(), form.getPassword().getValue());
                profileEntityManager.updateLastLoginDetails(auth.getName(), OrcidRequestUtil.getIpAddress(request));
                // 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();
                    form.setRedirectUrl(redirectUri);
                    LOGGER.info("OauthLoginController being sent to client browser: " + form.getRedirectUrl());
                    return form;
                }
                // Approve
                RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
                form.setRedirectUrl(view.getUrl());
                willBeRedirected = true;
            } catch (AuthenticationException ae) {
                if (ae.getCause() instanceof DisabledException) {
                    // Handle this message in angular to allow AJAX action
                    form.getErrors().add("orcid.frontend.security.orcid_deactivated");
                } else if (ae.getCause() instanceof UnclaimedProfileExistsException) {
                    String email = PojoUtil.isEmpty(form.getUserName()) ? null : form.getUserName().getValue();
                    String resendEmailUrl = createResendClaimUrl(email, request);
                    String errorMessage = getMessage("orcid.frontend.security.unclaimed_exists");
                    errorMessage = errorMessage.replace("{{resendClaimUrl}}", resendEmailUrl);
                    form.getErrors().add(errorMessage);
                } else {
                    form.getErrors().add(getMessage("orcid.frontend.security.bad_credentials"));
                }
            }
        }
    } else {
        form.setRedirectUrl(buildDenyRedirectUri(requestInfoForm.getRedirectUrl(), requestInfoForm.getStateParam()));
        willBeRedirected = true;
    }
    // not be redirected yet
    if (willBeRedirected) {
        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 form;
}
Also used : HashMap(java.util.HashMap) AuthenticationException(org.springframework.security.core.AuthenticationException) DisabledException(org.springframework.security.authentication.DisabledException) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) UnclaimedProfileExistsException(org.orcid.core.security.UnclaimedProfileExistsException) 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) SimpleSessionStatus(org.springframework.web.bind.support.SimpleSessionStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 4 with HttpSessionRequestCache

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

the class OauthAuthorizeController method authorize.

@RequestMapping(value = { "/oauth/custom/authorize.json" }, method = RequestMethod.POST)
@ResponseBody
public RequestInfoForm authorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthAuthorizeForm form) {
    RequestInfoForm requestInfoForm = (RequestInfoForm) request.getSession().getAttribute(REQUEST_INFO_FORM);
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession().getAttribute("authorizationRequest");
    Map<String, String> requestParams = new HashMap<String, String>(authorizationRequest.getRequestParameters());
    Map<String, String> approvalParams = new HashMap<String, String>();
    // Add the persistent token information
    if (form.getApproved()) {
        requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
        approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    } else {
        requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "false");
        approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "false");
    }
    requestParams.put(OrcidOauth2Constants.TOKEN_VERSION, OrcidOauth2Constants.PERSISTENT_TOKEN);
    // Check if the client have persistent tokens enabled
    requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false");
    if (hasPersistenTokensEnabled(requestInfoForm.getClientId()))
        // Then check if the client granted the persistent token
        if (form.getPersistentTokenEnabled())
            requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true");
    // strip /email/read-private scope if user has not consented
    if (requestInfoForm.containsEmailReadPrivateScope() && !form.isEmailAccessAllowed()) {
        requestInfoForm.removeEmailReadPrivateScope();
        requestParams.put(OrcidOauth2Constants.SCOPE_PARAM, requestInfoForm.getScopesAsString());
    }
    // Session status
    SimpleSessionStatus status = new SimpleSessionStatus();
    authorizationRequest.setRequestParameters(requestParams);
    // Authorization request model
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("authorizationRequest", authorizationRequest);
    // Approve
    RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth);
    requestInfoForm.setRedirectUrl(view.getUrl());
    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 : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) HashMap(java.util.HashMap) Authentication(org.springframework.security.core.Authentication) HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) RedirectView(org.springframework.web.servlet.view.RedirectView) RequestInfoForm(org.orcid.pojo.ajaxForm.RequestInfoForm) SimpleSessionStatus(org.springframework.web.bind.support.SimpleSessionStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 5 with HttpSessionRequestCache

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

the class RegistrationController method register.

@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView register(HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mav = new ModelAndView("register");
    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);
    LOGGER.debug("Saved url before registration is: " + (savedRequest != null ? savedRequest.getRedirectUrl() : " no saved request"));
    return mav;
}
Also used : HttpSessionRequestCache(org.springframework.security.web.savedrequest.HttpSessionRequestCache) ModelAndView(org.springframework.web.servlet.ModelAndView) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

HttpSessionRequestCache (org.springframework.security.web.savedrequest.HttpSessionRequestCache)12 SavedRequest (org.springframework.security.web.savedrequest.SavedRequest)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 RequestInfoForm (org.orcid.pojo.ajaxForm.RequestInfoForm)4 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)4 HashMap (java.util.HashMap)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 Authentication (org.springframework.security.core.Authentication)3 SimpleSessionStatus (org.springframework.web.bind.support.SimpleSessionStatus)3 RedirectView (org.springframework.web.servlet.view.RedirectView)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 HttpSession (javax.servlet.http.HttpSession)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 RedirectMismatchException (org.springframework.security.oauth2.common.exceptions.RedirectMismatchException)2 URI (java.net.URI)1 Locale (java.util.Locale)1 Matcher (java.util.regex.Matcher)1 FilterChain (javax.servlet.FilterChain)1 ServletException (javax.servlet.ServletException)1