如果未通过身份验证,则将重定向重定向到登录 - Spring security

时间:2021-06-03 00:08:51

标签: reactjs redirect spring-security axios

我有一个 Java/Jsf Web 应用程序,其中包含具有基于 Spring Security 会话的身份验证的 Rest API。

我目前正在构建一个使用此 API 的 React 小应用程序,并希望在未登录时将用户重定向到登录 (jsf) 页面。

到目前为止,我只是将登录页面作为数据返回。 不确定这是否必须在 Spring 或 React 端修复,以及如何解决。

谢谢

getSchedulesByFarmAndDate(farmId, startDate, endDate) {
    return axios.get(
      authService.getApiUrl() +
      `/reports/schedules/filterByFarmAndDate?id=${farmId}`, { withCredentials: true }
    );
  }

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

我遇到的问题是我的 Java 应用程序已经有一个登录页面 (JSF),因此除非我调用 API,否则无法在 React 中知道用户是否已登录。 通过在 Spring 安全配置中执行此操作,我想出了一种从 Spring 返回 401 的方法:

http.exceptionHandling().defaultAuthenticationEntryPointFor(
   getRestAuthenticationEntryPoint(),
   new AntPathRequestMatcher("/api/**")
);

private AuthenticationEntryPoint getRestAuthenticationEntryPoint({
    return new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
}

这样,如果 API 向 React 返回 401 代码,我将重定向到登录页面。这不是最干净的方法,但可以作为起点。