Example usage for org.springframework.security.web.savedrequest SavedRequest getRedirectUrl

List of usage examples for org.springframework.security.web.savedrequest SavedRequest getRedirectUrl

Introduction

In this page you can find the example usage for org.springframework.security.web.savedrequest SavedRequest getRedirectUrl.

Prototype

String getRedirectUrl();

Source Link

Usage

From source file:org.socialsignin.springsocial.security.signup.AbstractSignUpController.java

@RequestMapping(value = "", method = RequestMethod.POST)
public String signUpSubmit(ServletWebRequest request, @ModelAttribute("signUpForm") P signUpForm,
        BindingResult result) {//from www .  j a  v a 2s.  co  m
    Connection<?> connection = getProviderSignInUtils().getConnectionFromSession(request);

    String userId = signUpUser(request, signUpForm, result);
    if (result.hasErrors() || userId == null) {
        return signUpView;
    }
    springSocialSecuritySignInService.signIn(userId, connection, request);
    if (useSocialAuthenticationFilter) {
        // Attempt to determine the original requested url if access was originally denied
        SavedRequest savedRequest = requestCache.getRequest(request.getRequest(), request.getResponse());
        if (savedRequest != null) {
            String redirectUrl = savedRequest.getRedirectUrl();
            if (redirectUrl != null && savedRequest.getMethod().equalsIgnoreCase("get")) {
                return "redirect:" + redirectUrl;
            }
        }

        return "redirect:/";
    } else {
        return "redirect:" + authenticateUrl;
    }

}

From source file:org.socialsignin.springsocial.security.signin.SpringSocialSecurityConnectInterceptor.java

/**
 * This callback 1)  Ensures that 2 different local users
 * cannot share the same 3rd party connection 2) Updates the current
 * user's authentication if the set of roles they are assigned
 * needs to change now that this connection has been made.
 * 3) Looks for a request previously saved by an access denied
 * handler, and if present, sets the url of this original
 * pre-authorisation request as a session attribute
 * //from   ww  w.ja v  a2 s  .  co  m
 */
@Override
public void postConnect(Connection<S> connection, WebRequest webRequest) {

    super.postConnect(connection, webRequest);

    /**
     * User roles are generated according to connected
     * providers in spring-social-security
     * 
     * Now that this connection has been made,
     * doe we need to update the user roles?
     * 
     * If so, update the current user's authentication and update
     * remember-me services accordingly.
     */
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    Collection<? extends GrantedAuthority> existingAuthorities = authentication.getAuthorities();

    GrantedAuthority newAuthority = userAuthoritiesService.getProviderAuthority(connection.getKey());

    if (!existingAuthorities.contains(newAuthority)) {

        Authentication newAuthentication = authenticationFactory
                .updateAuthenticationForNewConnection(authentication, connection);
        SecurityContextHolder.getContext().setAuthentication(newAuthentication);

        if (rememberMeServices != null && webRequest instanceof ServletWebRequest) {

            ServletWebRequest servletWebRequest = ((ServletWebRequest) webRequest);
            rememberMeServices.loginSuccess(servletWebRequest.getRequest(), servletWebRequest.getResponse(),
                    newAuthentication);
        }
    }

    /**
     * This connection may have been instigated by an 
     * access denied handler which may have saved the
     * original request made by the user before their access
     * was denied.  
     * 
     * Spring Social sends the user to a particular view
     * on completion of connection.  We may wish to offer the
     * user a "continue" link on this view, allowing their
     * original request (if saved by the access denied handler)
     * to be re-attempted
     *
     */
    if (webRequest instanceof ServletWebRequest) {
        ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
        SavedRequest savedRequest = requestCache.getRequest(servletWebRequest.getRequest(),
                servletWebRequest.getResponse());
        if (savedRequest != null) {
            String redirectUrl = savedRequest.getRedirectUrl();
            if (redirectUrl != null && savedRequest.getMethod().equalsIgnoreCase("get")) {
                servletWebRequest.setAttribute(SAVED_REQUEST_URL_ATTRIBUTE_NAME, savedRequest.getRedirectUrl(),
                        RequestAttributes.SCOPE_SESSION);
            }
        }
    }
}

From source file:com.trailmagic.image.ui.LogoutController.java

@RequestMapping("/logout")
public void handleRequestInternal(HttpServletRequest req, HttpServletResponse res) throws Exception {
    SavedRequest savedRequest = requestCache.getRequest(req, res);

    HttpSession session = req.getSession(false);
    session.invalidate();//  w w  w .  ja  v a  2  s  . c  o  m

    Cookie terminate = new Cookie(TokenBasedRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, null);
    terminate.setMaxAge(0);
    res.addCookie(terminate);

    if (savedRequest != null) {
        res.sendRedirect(savedRequest.getRedirectUrl());
    } else {
        res.sendRedirect("/photo/albums/");
    }
}

From source file:nl.surfnet.spring.security.opensaml.AuthenticationFailureHandlerImpl.java

public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authenticationException) throws IOException, ServletException {

    SavedRequest savedRequest = requestCache.getRequest(request, response);

    logger.debug("saved Request: {}", savedRequest);

    if (authenticationException instanceof IdentityProviderAuthenticationException && savedRequest != null) {

        logger.warn("Authn Failure reported by the IDP.", authenticationException);
        logger.debug("Retry original request of {}", savedRequest.getRedirectUrl());
        response.sendRedirect(savedRequest.getRedirectUrl());
    } else {/*from   www.j a  v  a  2 s .c o  m*/
        logger.warn("Unrecoverable authn failure. Sending to Forbidden", authenticationException);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}

From source file:org.glassmaker.spring.oauth.OAuth2AuthenticationFilter.java

public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws ServletException, IOException {

    SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response);

    if (savedRequest == null) {
        return;/*from ww  w . j  ava2 s.co  m*/
    }
    HttpSession session = request.getSession();
    session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

    // Use the DefaultSavedRequest URL
    String targetUrl = savedRequest.getRedirectUrl();
    logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
    response.sendRedirect(targetUrl);
}

From source file:cec.easyshop.storefront.security.StorefrontAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication authentication) throws IOException, ServletException {
    //if redirected from some specific url, need to remove the cachedRequest to force use defaultTargetUrl
    final RequestCache requestCache = new HttpSessionRequestCache();
    final SavedRequest savedRequest = requestCache.getRequest(request, response);
    for (final String redirectUrlForceDefaultTarget : getListRedirectUrlsForceDefaultTarget()) {
        if (savedRequest != null && savedRequest.getRedirectUrl().contains(redirectUrlForceDefaultTarget)) {
            requestCache.removeRequest(request, response);
            break;
        }/*  www.  j ava2s .c  o m*/
    }

    getCustomerFacade().loginSuccess();
    request.setAttribute(CART_MERGED, Boolean.FALSE);

    if (!getCartFacade().hasEntries()) {
        getSessionService().setAttribute(WebConstants.CART_RESTORATION_SHOW_MESSAGE, Boolean.TRUE);
        try {
            getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                    getCartFacade().restoreSavedCart(null));
        } catch (final CommerceCartRestorationException e) {
            getSessionService().setAttribute(WebConstants.CART_RESTORATION_ERROR_STATUS,
                    WebConstants.CART_RESTORATION_ERROR_STATUS);
        }
    } else {
        final String sessionCartGuid = getCartFacade().getSessionCartGuid();
        final String mostRecentSavedCartGuid = getMostRecentSavedCartGuid(sessionCartGuid);
        if (StringUtils.isNotEmpty(mostRecentSavedCartGuid)) {
            getSessionService().setAttribute(WebConstants.CART_RESTORATION_SHOW_MESSAGE, Boolean.TRUE);
            try {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                        getCartFacade().restoreCartAndMerge(mostRecentSavedCartGuid, sessionCartGuid));
                request.setAttribute(CART_MERGED, Boolean.TRUE);
            } catch (final CommerceCartRestorationException e) {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION_ERROR_STATUS,
                        WebConstants.CART_RESTORATION_ERROR_STATUS);
            } catch (final CommerceCartMergingException e) {
                LOG.error("User saved cart could not be merged");
            }
        }
    }

    getBruteForceAttackCounter().resetUserCounter(getCustomerFacade().getCurrentCustomerUid());
    super.onAuthenticationSuccess(request, response, authentication);
}

From source file:de.hybris.platform.acceleratorstorefrontcommons.security.StorefrontAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication authentication) throws IOException, ServletException {
    //if redirected from some specific url, need to remove the cachedRequest to force use defaultTargetUrl
    final RequestCache requestCache = new HttpSessionRequestCache();
    final SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest != null) {
        for (final String redirectUrlForceDefaultTarget : getListRedirectUrlsForceDefaultTarget()) {
            if (savedRequest.getRedirectUrl().contains(redirectUrlForceDefaultTarget)) {
                requestCache.removeRequest(request, response);
                break;
            }/*from w  w  w.  j av  a2 s  . c om*/
        }
    }
    getCustomerFacade().loginSuccess();
    request.setAttribute(WebConstants.CART_MERGED, Boolean.FALSE);

    // Check if the user is in role admingroup
    if (!isAdminAuthority(authentication)) {
        getCartRestorationStrategy().restoreCart(request);
        getBruteForceAttackCounter().resetUserCounter(getCustomerFacade().getCurrentCustomerUid());
        super.onAuthenticationSuccess(request, response, authentication);
    } else {
        LOG.warn("Invalidating session for user in the " + Constants.USER.ADMIN_USERGROUP + " group");
        invalidateSession(request, response);
    }
}

From source file:de.hybris.platform.b2bacceleratoraddon.security.B2BStorefrontAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication authentication) throws IOException, ServletException {
    //if redirected from some specific url, need to remove the cachedRequest to force use defaultTargetUrl
    final RequestCache requestCache = new HttpSessionRequestCache();
    final SavedRequest savedRequest = requestCache.getRequest(request, response);

    if (savedRequest != null) {
        for (final String redirectUrlForceDefaultTarget : getListRedirectUrlsForceDefaultTarget()) {
            if (savedRequest.getRedirectUrl().contains(redirectUrlForceDefaultTarget)) {
                requestCache.removeRequest(request, response);
                break;
            }//from w w w.j  a va2s  . c om
        }
    }

    getCustomerFacade().loginSuccess();
    request.setAttribute(CART_MERGED, Boolean.FALSE);

    // Check if the user is in role admingroup
    if (!isAdminAuthority(authentication)) {
        if (!getCartFacade().hasEntries()) {
            restoreSavedCart();
        } else {
            restoreSavedCartAndMerge(request);
        }

        getBruteForceAttackCounter().resetUserCounter(getCustomerFacade().getCurrentCustomerUid());
        super.onAuthenticationSuccess(request, response, authentication);
    } else {
        LOG.warn("Invalidating session for user in the " + Constants.USER.ADMIN_USERGROUP + " group");
        invalidateSession(request, response);
    }
}

From source file:it.smartcommunitylab.aac.controller.AuthController.java

/**
 * Redirect to the login type selection page.
 * /*w  ww. ja  v a2s.c o  m*/
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/login")
public ModelAndView login(HttpServletRequest req, HttpServletResponse res) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();
    Map<String, String> authorities = attributesAdapter.getWebAuthorityUrls();

    SavedRequest savedRequest = requestCache.getRequest(req, res);
    String target = savedRequest != null ? savedRequest.getRedirectUrl() : prepareRedirect(req, "/dev");
    req.getSession().setAttribute("redirect", target);

    Map<String, String> resultAuthorities = authorities;
    // If original request has client_id parameter, reduce the authorities to the ones of the client app
    if (savedRequest != null) {
        String[] clientIds = savedRequest.getParameterValues(OAuth2Utils.CLIENT_ID);
        if (clientIds != null && clientIds.length > 0) {
            String clientId = clientIds[0];

            Set<String> idps = clientDetailsAdapter.getIdentityProviders(clientId);
            String[] loginAuthoritiesParam = savedRequest.getParameterValues("authorities");
            String loginAuthorities = "";
            if (loginAuthoritiesParam != null && loginAuthoritiesParam.length > 0) {
                loginAuthorities = StringUtils.arrayToCommaDelimitedString(loginAuthoritiesParam);
            }

            Set<String> all = null;
            if (StringUtils.hasText(loginAuthorities)) {
                all = new HashSet<String>(Arrays.asList(loginAuthorities.split(",")));
            } else {
                all = new HashSet<String>(authorities.keySet());
            }
            resultAuthorities = new HashMap<String, String>();
            for (String idp : all) {
                if (authorities.containsKey(idp) && idps.contains(idp))
                    resultAuthorities.put(idp, authorities.get(idp));
            }

            if (resultAuthorities.isEmpty()) {
                model.put("message", "No Identity Providers assigned to the app");
                return new ModelAndView("oauth_error", model);
            }
            req.getSession().setAttribute(OAuth2Utils.CLIENT_ID, clientId);
            if (resultAuthorities.size() == 1 && !resultAuthorities.containsKey(Config.IDP_INTERNAL)) {
                return new ModelAndView(
                        "redirect:" + Utils.filterRedirectURL(resultAuthorities.keySet().iterator().next()));
            }
        }
    }
    req.getSession().setAttribute("authorities", resultAuthorities);

    return new ModelAndView("login", model);
}