ReactJS + Spring Social(Facebook)+在身份验证后重定向回React

时间:2017-08-01 00:58:42

标签: spring facebook authentication spring-social spring-social-facebook

我在http://localhost:8080

上运行我的后端(spring boot)应用程序

我在http://localhost:3000

上运行了我的前端(react js)应用程序

我的前端SignIn按钮通过Facebook(http://localhost:8080/connect/facebook)进行身份验证,后者通过后端应用程序进行oauth跳舞。这是使用spring-social插件免费提供的。

成功通过身份验证后,我将facebookConnected.html重定向到http://localhost:8080/handle-successful-authentication,这是我的后端应用程序中处理验证后逻辑的端点。

一旦我处理完这个问题,我该如何控制回到我的前端?

1 个答案:

答案 0 :(得分:0)

也许您应该检查 referer header filed 并查看它是否符合您的需求:在成功登录过程后使用它重定向回来。检查this answer是否使用 SimpleUrlAuthenticationSuccessHandler

@Bean
public AuthenticationSuccessHandler successHandler() {
SimpleUrlAuthenticationSuccessHandler handler = new SimpleUrlAuthenticationSuccessHandler();
    handler.setUseReferer(true);
    return handler;
}

或者,如果您手动在弹簧中配置更多部分,则可以使用this answer 在过滤阶段获取referer url并将其保存在会话中。 该答案的一个修改可能是:扩展OAuth2ClientAuthenticationProcessingFilter并在doFilter中获取referer值

public class MyOAuth2ClientAuthenticationProcessingFilter extends OAuth2ClientAuthenticationProcessingFilter {
...
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    String referrer = request.getHeader("Referer");        
    if (null != referrer)
        request.getSession().setAttribute("url_prior_login", referrer);

    super.doFilter(req, res, chain);
    }
}

因此您可以在处理完成后的“...处理成功身份验证”后重定向。 - 但是当我看到这个重定向是开销时,如果你需要来自社交oauth提供者的更多用户详细信息,请尝试将此逻辑放在其他地方(例如,UserInfoTokenServices中的successHandler()或pricipalExtractor())

successHandler()看起来像这样:

@Bean
public AuthenticationSuccessHandler successHandler() { 
    AuthenticationSuccessHandler rst = new AuthenticationSuccessHandler() {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                Authentication authentication) throws IOException, ServletException {
            ...
            HttpSession session = request.getSession();
            String redirectUrl = null;
            if (session != null) {
                redirectUrl = (String) session
                        .getAttribute("url_prior_login");

            if (null == redirectUrl || redirectUrl.trim().length() <= 0)
                redirectUrl = "http://your_default_redirect_url";

            response.sendRedirect(redirectUrl); 
        };
        return rst;
}

无论如何,检查春天docs