如何使用Spring Security允​​许访问特定的React Hash路由?

时间:2017-10-18 17:14:34

标签: reactjs spring-security react-router jwt spring-security-oauth2

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

当对应用程序发出请求时,所有请求都以/ app /进入,而不是/ app /#/ Login,/ app /#/ Home等。这对我来说很有意义,因为路由是在客户端呈现正确的路由,但它会导致尝试保护应用程序时出现问题。为了允许访问Login路由,我需要允许访问Spring Security中的/ app / all,这将打开所有内容。

是否可以在Spring Security中保护React Hash Route,或者我是否必须在路由器的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()
        ;
    }
}

提前致谢!

1 个答案:

答案 0 :(得分:1)

你做不到。在构建SPA时,您需要转移安全焦点以保护SPA正在访问的API端点,而不是保护“页面”或“SPA路由”。因此,只需保护为SPA提供数据和功能的服务器端点。

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

这并不意味着您不应该在SPA中拥有代码来隐藏禁止链接或阻止用户访问该路由 - 您应该因为它可以提供更好的用户体验。只要知道隐藏SPA中的路由纯粹是为了UX,而不是安全。通过保护api来处理安全性。