Как я могу перенаправить пользователя после успешного входа на разные страницы, основываясь на его предыдущей странице? - PullRequest
1 голос
/ 12 мая 2019

Я перенаправляю пользователя на домашнюю страницу с установленным по умолчанию "URL-адресом цели" на "/". Однако мне нужно перенаправить пользователя, если он войдет на страницу продукта (/ p /) или на страницу поиска (/ search). Как я мог сделать это? Я еще не настолько осведомлен о Spring Security и перенаправлениях.

Я попытался перехватить запрос в методе onAuthenticationSuccess () в моем AuthenticationSuccessHandler и проверить URL-адрес, если он содержит страницу продукта или URL-адрес страницы поиска.

В AuthenticationSuccessHandler:

if (!response.isCommitted()) {
   super.onAuthenticationSuccess(request,response,authentication);
}

В файле spring-security-config.xml:

<bean id="authenticationSuccessHandler" class ="com.storefront.AuthenticationSuccessHandler" scope="tenant">
<property name="rememberMeCookieStrategy" ref="rememberMeCookieStrategy" />
<property name="customerFacade" ref="customerFacade" />
<property name="sCustomerFacade" ref="sCustomerFacade" />
<property name="sProductFacade" ref="sProductFacade" />
<property name="defaultTargetUrl" value="/" />
<property name="useReferer" value="true" />
<property name="requestCache" value="httpSessionRequestCache" />

Ожидаемые результаты будут:

  1. Когда пользователь входит в систему на странице продукта, он возвращается на страницу продукта, на которой он находился.
  2. Когда пользователь входит на страницу поиска, он возвращается на страницу поиска, на которой он находился.
  3. Если пользователь входит в систему, не находясь на странице продукта или поиска, он перенаправляется на домашнюю страницу.

Ответы [ 2 ]

0 голосов
/ 13 мая 2019

Hybris OOTB (я имею в виду V6.7) имеет функцию, в которой вы можете перечислить URL-адреса, для которых вы хотите перенаправить на URL-адрес цели по умолчанию.Идея здесь состоит в том, чтобы иметь другой список (или заменить существующий) обратной логикой, которая разрешает только заданные URL-адреса и перенаправляет все другие URL-адреса на целевые URL-адреса по умолчанию.

В OOTB вы можете увидеть listRedirectUrlsForceDefaultTarget в spring-security-config.xml, где можно определить список URL-адресов, которые вы хотите перенаправить на цель по умолчанию.Как показано ниже.

<alias name="defaultLoginAuthenticationSuccessHandler" alias="loginAuthenticationSuccessHandler"/>
<bean id="defaultLoginAuthenticationSuccessHandler" class="de.hybris.platform.acceleratorstorefrontcommons.security.StorefrontAuthenticationSuccessHandler" >
    <property name="customerFacade" ref="customerFacade" />
    <property name="defaultTargetUrl" value="#{'responsive' == '${commerceservices.default.desktop.ui.experience}' ? '/' : '/my-account'}"/>
    <property name="useReferer" value="true"/>
    <property name="requestCache" ref="httpSessionRequestCache" />
    <property name="uiExperienceService" ref="uiExperienceService"/>
    <property name="cartFacade" ref="cartFacade"/>
    <property name="customerConsentDataStrategy" ref="customerConsentDataStrategy"/>
    <property name="cartRestorationStrategy" ref="cartRestorationStrategy"/>
    <property name="forceDefaultTargetForUiExperienceLevel">
        <map key-type="de.hybris.platform.commerceservices.enums.UiExperienceLevel" value-type="java.lang.Boolean">
            <entry key="DESKTOP" value="false"/>
            <entry key="MOBILE" value="false"/>
        </map>
    </property>
    <property name="bruteForceAttackCounter" ref="bruteForceAttackCounter" />
    <property name="restrictedPages">
        <list>
            <value>/login</value>
        </list>
    </property>
    <property name="listRedirectUrlsForceDefaultTarget">
        <list>/example/redirect/todefault</list>
    </property>
</bean>

StorefrontAuthenticationSuccessHandler

@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;
                }
            }
        }

      //...
    }

Теперь поменяйте местами эту логику, объявив новый список (скажем, listAllowedRedirectUrls) или заменив listRedirectUrlsForceDefaultTarget на listAlrededRed в listAllowedRed* и внесите соответствующие изменения в SuccessHandler.Как

<property name="listAllowedRedirectUrls">
    <list>/p/</list>
    <list>/search</list>
</property>

StorefrontAuthenticationSuccessHandler

    if (savedRequest != null)
    {
        for (final String listAllowedRedirectUrl : getListAllowedRedirectUrls())
        {
            if ( ! savedRequest.getRedirectUrl().contains(listAllowedRedirectUrl))
            {
                requestCache.removeRequest(request, response);
                break;
            }
        }
    }

Вы должны сделать те же изменения для / login / checkout объявления обработчика (defaultLoginCheckoutAuthenticationSuccessHandler) также.

0 голосов
/ 12 мая 2019

Вы можете расширить AbstractLoginPageController для запуска собственного сценария. Сохраните URL реферера в методе doLogin в httpSessionRequestCache. Затем проверьте, отфильтруйте и верните URL-адрес реферера в методе getSuccessRedirect .

...