如何使用 Spring 安全性允许访问特定的 React Hash 路由?

How can I allow access to specific React Hash Routes using Spring Security?

我试图限制未经身份验证的用户访问我们的 Reactjs 单页应用程序中的任何路由。我们使用 HashRouter 来处理 UI 端的路由,所以我们的 url 看起来像 http://localhost/app/#/Home, http://localhost/app/#/Login,等等。我们使用 Spring Security OAuth2 with JWT。

当向应用程序发出请求时,所有请求都以 /app/ 的形式出现,而不是 /app/#/Login、/app/#/Home 等。这对我来说很有意义,因为路由已完成在客户端呈现正确的路线,但它会导致尝试保护应用程序的问题。为了允许访问登录路由,我需要在 Spring 安全性中允许所有访问 /app/,这会打开所有内容。

是否可以在 Spring 安全性中保护 React 哈希路由,或者我必须在路由器的 UI 端处理这个问题?

登录配置

@EnableWebSecurity(debug = true)
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class LoginConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/app/#/login")
                .httpBasic().disable()
                .formLogin().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers(HttpMethod.GET, "/favicon.ico").permitAll()
                .antMatchers("/app/#/login").permitAll()
                .anyRequest().authenticated()
        ;
    }
}

登录配置授予所有人访问权限

@EnableWebSecurity(debug = true)
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class LoginConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/app/**")
                .httpBasic().disable()
                .formLogin().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers(HttpMethod.GET, "/favicon.ico").permitAll()
                .antMatchers("/app/**").permitAll()
                .anyRequest().authenticated()
        ;
    }
}

所有其他请求的默认配置

@EnableWebSecurity(debug = true)
@Configuration
@Order(2)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic().disable()
                .formLogin().disable()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers(HttpMethod.GET, "/**/favicon.ico").permitAll()
                .antMatchers(HttpMethod.POST, "/oa/oauth/token").permitAll()
                .anyRequest().authenticated()
        ;
    }
}

提前致谢!

你不能。构建 SPA 时,您将安全重点转移到保护 SPA 正在访问的 API 个端点,而不是保护 "pages" 或 "SPA routes"。因此,只需保护为 SPA 提供数据和功能的服务器端点。

例如,如果不允许用户访问 "admin" 功能,则不要尝试阻止路由 /app/#Admin,而是确保并阻止所有与管理员相关的 api 端点(如 /api/admin/api/adduser、...)。

这并不意味着您不应该在 SPA 中使用代码来隐藏禁止链接或阻止用户访问该路由——您应该这样做,因为它有助于更好的用户体验。只知道在 SPA 中隐藏路由纯粹是为了用户体验,而不是为了安全。通过保护 api.

来处理安全性