Spring Boot React Google OAuth2注销未重定向

时间:2019-02-11 08:57:06

标签: spring-boot react-redux axios spring-security-oauth2

我正在编码一个Web应用程序,它将允许用户使用Google OAuth2帐户登录。我在前端使用Node React,在后端使用Spring Boot。到目前为止,我已经可以使用登录功能。注销功能似乎也有些起作用,因为我能够在控制台日志中看到预期的响应。我遇到的麻烦是我希望在单击注销按钮后将重定向到http://localhost:8080/greeting,但是这没有发生。我究竟做错了什么?

Header.js

class Header extends Component {
  renderContent(){
    switch (this.props.auth){
      case null:
        return;
      case false:
        return <li><a href="login/google">Login</a></li>
      default:
        return <li><button onClick={this.handleLogout} >Logout</button></li>
    }
  }
  ...
handleLogout = () => {
  axios({method: 'post',
         url: "http://localhost:8080/logout",
         withCredentials: true,
         headers: {'X-XSRF-TOKEN': cookies.get('XSRF-TOKEN')}
        })
  .catch(error => console.log('BAD', error))
  .then(reponse => console.log('GOOD', reponse));
        return response;            
    }
}                     

WebApp.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/**")
        .authorizeRequests()
        .antMatchers(
      "/**",
                 "/login",
                "/greeting",
                "/error**",
                "/api/**").permitAll()
      .anyRequest().authenticated()
      .and()
    .exceptionHandling()
      .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))
      .and()
    .logout().logoutSuccessUrl("/greeting").permitAll()
            .and()
    .csrf()
      .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
      .and()

3 个答案:

答案 0 :(得分:1)

axios调用不会为您重定向,如果HTTP响应代码指示重定向,则必须在前端自行处理

答案 1 :(得分:1)

您的handleLogout函数向服务器执行AJAX请求-因此,任何重定向响应都将由您的回调函数而非浏览器处理-并且重定向不会发生。

您可以进行同步。请求到您的服务器(不是AJAX),也可以在客户端执行重定向(在回调中使用一些JS代码)。

我建议第一种选择:

<li><button onClick={this.handleLogout} >Logout</button></li>

成为:

<li><a href="http://localhost:8080/logout" >Logout</a></li>


更新1: 如果您强制使用HTTP POST方法执行请求,则可以在“ onSuccess”回调中执行重定向( axios理解重定向并遵循重定向的链接):

handleLogout = () => {
  axios({method: 'post',
         url: "http://localhost:8080/logout",
         withCredentials: true,
         headers: {'X-XSRF-TOKEN': cookies.get('XSRF-TOKEN')}
        })
  .catch(error => console.log('BAD', error))
  .then(reponse => {
    window.location.href = "http://localhost:8080/greeting";
  });
} 

答案 2 :(得分:0)

更新:这是我根据jonash建议提出的解决方案。我认为这是一个临时性的解决方案,直到我学到足够的React以使用最佳实践进行重构为止。

更新后的Header.js

handleLogout = () => {
  axios({method: 'post',
         url: "http://localhost:8080/logout",
         withCredentials: true,
         headers: {'X-XSRF-TOKEN': cookies.get('XSRF-TOKEN')}
        })
  .catch(error => console.log('BAD', error))
  .then(response => { window.location = response.request.responseURL });
相关问题