【问题标题】:Authentication with React Router and Spring Security使用 React Router 和 Spring Security 进行身份验证
【发布时间】:2020-05-28 14:14:18
【问题描述】:

我正在使用 React 和 Spring Boot 构建一个全栈应用程序,但遇到了一个我在任何地方都找不到答案的问题。

我试图实现的行为如下:

  1. 如果用户想要访问登录或注册页面,如果他们通过身份验证,我想将用户重定向到主页。 isAuthenticated 是 redux 中的一个标志,我在应用首次加载时设置。

  2. 如果用户未通过身份验证并尝试访问主页,我还想将用户重定向到登录页面。

第一个目标运行良好,因为有很多教程解释如何使用 react-router 来实现这一目标,但第一个目标似乎无法在生产中正常运行。

我有一个 Spring Boot 应用程序在后端作为 REST API 运行,我正在使用 eirslett/frontend-maven-plugin 将我的前端和后端打包到一个 jar 中以进行部署。

当我在本地分别启动前端和后端作为两个开发服务器时,如果我未登录(如果我尝试通过 react-router 访问安全路由),应用程序会将我重定向到登录页面。但是,如果我在未经过身份验证时直接进入 /login 路由,它会给我一个错误 401 页面,但如果我尝试访问主路由并被重定向到 /login,它不会给我错误。因此,即使我很好地重定向到 /login,我也无法刷新页面,否则会出现错误 401。

我的 React 前端的根组件如下所示,它使用了 React-router:

function App() {
  return (
    <Provider store={store}>
      <ConnectedRouter history={history}>
        <div className='AppContainer'>
          <Navbar />
          <Switch>
            <PublicRoute path='/login' component={Login} />
            <PublicRoute path='/register' component={Register} />
            <PrivateRoute path='/' component={Todos} />
          </Switch>
        </div>
      </ConnectedRouter>
    </Provider>
  );
}

export default App;

我使用的 PublicRoute 和 PrivateRoute 组件如下所示:

function PrivateRoute({ component: Component, isAuthenticated, ...rest }) {
  return (
    <Route
      {...rest}
      render={props =>
        isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{ pathname: '/login', state: { from: props.location } }}
          />
        )
      }
    ></Route>
  );
}

const mapStateToProps = state => ({
  isAuthenticated: state.auth.isAuthenticated
});

export default connect(mapStateToProps)(PrivateRoute);
function PublicRoute({ component: Component, isAuthenticated, ...rest }) {
  return (
    <Route
      {...rest}
      render={props =>
        isAuthenticated ? (
          <Redirect to={{ pathname: '/', state: { from: props.location } }} />
        ) : (
          <Component {...props} />
        )
      }
    ></Route>
  );
}

const mapStateToProps = state => ({
  isAuthenticated: state.auth.isAuthenticated
});

export default connect(mapStateToProps)(PublicRoute);

有人知道发生了什么吗?我觉得问题的存在是因为我配置 PublicRoute 组件和 Spring Security 的方式,但我不知道如何让它们一起工作。或者,根据我的天真理解,我的前端应用程序只有在我第一次访问我的根路由时才会加载,因此它会将我重定向到 /login 就好了;但是如果我访问的第一个页面是 /login,则不会加载 React 的根组件,因此该路由受我的 Spring Security 配置的保护。但是有没有办法解决这个问题?

感谢任何帮助!

【问题讨论】:

    标签: reactjs spring spring-security react-router


    【解决方案1】:

    我意识到我使用的是BrowserRouter 而不是HashRouter,这就是我得到401 和404 的原因。react-router 文档实际上很好地解释了为什么应该使用@ 987654324@here.

    【讨论】:

      猜你喜欢
      • 2011-10-17
      • 2014-07-03
      • 2012-11-27
      • 2017-08-14
      • 2018-11-07
      • 1970-01-01
      • 2018-08-09
      • 2012-11-10
      相关资源
      最近更新 更多