spring boot + security + oauth2 + react + csrf token

时间:2017-04-18 19:04:21

标签: spring security reactjs oauth-2.0 csrf

我正在使用oauth2处理spring boot 1.5.2安全性,我也在使用reactjs。我有单独的身份验证服务器用于用户身份验证,它正常工作。当用户点击它时我有注销链接应该注销但我在日志中收到此错误:

http://localhost:8080/logout

找到无效的CSRF令牌

我正在分享我的代码:

  1. App.js

    class App extends React.Component {
    constructor() {
      super();
      this.state = {
        authenticated: false,
        id: '',
        greeting:''
      }
    }
    
    componentDidMount() {
      client({method: 'GET', path: '/user'}).then(response => {
        if(response.entity.name != null && response.entity.name.length>0) {
          this.setState({authenticated: true});
          console.log(response);
          client({method: 'GET', path: '/resource'}).then(response => {
            console.log(response);
          });
        } else {
          this.setState({authenticated: false});
        }
      });
    
      if(this.state.authenticated === true) {
        console.log("*********** if user is authenticated **********");
        client({method: 'GET', path: '/resource'}).then(response => {
          console.log(response);
        })
      }
    }
    
    // handleLogin = (e) => {
    //   alert('**************handleLogin()***************')
    //   client({method: 'GET', path: '/login'});
    // }
    
    handleLogout = (e) => {
      client({
              method: 'POST',
              path: '/logout'
              }).then(response => {
        console.log(response);
      });
    }      
    
    render() {
      return (
        <div>
          <Navbar>
            <Navbar.Header>
              <Navbar.Brand>
                <a href="#">Client App</a>
              </Navbar.Brand>
            </Navbar.Header>
            <Nav>
              <NavItem>Home</NavItem>
              <NavItem href="/login">Sign In</NavItem>
              { this.state.authenticated ?
                <NavItem onClick={this.handleLogout}>Sign Out</NavItem> : null }
            </Nav>
          </Navbar>
            <div className="container">
              { this.state.authenticated ? <UserDetails/> : <WelcomeMSG/> }
            </div>
          </div>
      );
     }
    
    }
    
    ReactDOM.render(
     <App/>,
     document.getElementById('app')
    )
    
  2. 客户端应用程序主类

    @SpringBootApplication
    @EnableZuulProxy
    @EnableOAuth2Sso
    public class OauthUiApplication extends WebSecurityConfigurerAdapter {
    
    public static void main(String[] args) {
        SpringApplication.run(OauthUiApplication.class, args);
    }
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .logout()
            .and()
            .antMatcher("/**")
            .authorizeRequests()
                .antMatchers("/index.html", "/home.html", "/**", "/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .csrf()
                .csrfTokenRepository(csrfTokenRepository())
                .and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
            // @formatter:on
    }
    
    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                    HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                        .getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "XSRF-Token");
                    String token = csrf.getToken();
                    if (cookie == null || token != null
                            && !token.equals(cookie.getValue())) {
                        cookie = new Cookie("XSRF-Token", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }
    
    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-Token");
        return repository;
     }
    }
    
  3. 任何建议都会很明显。

0 个答案:

没有答案