Ste*_*eve 4 spring-security jwt reactjs spring-security-oauth2 react-router
我试图限制未经身份验证的用户访问我们的 Reactjs 单页应用程序中的任何路由。我们使用 HashRouter 来处理 UI 端的路由,因此我们的 url 看起来像http://localhost/app/#/Home、http://localhost/app/#/Login等。我们使用 Spring Security使用 JWT 的 OAuth2。
当向应用程序发出请求时,所有请求都以 /app/ 形式传入,而不是 /app/#/Login、/app/#/Home 等。这对我来说很有意义,因为路由是在客户端上完成渲染的正确的路线,但它会导致尝试保护应用程序的问题。为了允许访问登录路由,我需要允许 Spring Security 中的所有人访问 /app/,这将打开所有内容。
是否可以在 Spring Security 中保护 React Hash 路由,或者我必须在路由器的 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()
;
}
}
Run Code Online (Sandbox Code Playgroud)
登录配置授予所有人访问权限
@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()
;
}
}
Run Code Online (Sandbox Code Playgroud)
所有其他请求的默认配置
@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()
;
}
}
Run Code Online (Sandbox Code Playgroud)
提前致谢!
你不能。构建 SPA 时,您将安全重点转移到保护 SPA 访问的 API 端点,而不是保护“页面”或“SPA 路由”。因此,只需保护向 SPA 提供数据和功能的服务器端点即可。
例如,如果不允许用户访问“admin”功能,/app/#Admin您不必尝试阻止路由,而是确保并阻止所有与管理相关的 api 端点(例如/api/admin,,/api/adduser...)。
这并不意味着您不应该在SPA 中使用代码来隐藏禁止的链接或阻止用户访问该路线 - 您应该这样做,因为它可以带来更好的用户体验。只需要知道,在 SPA 中隐藏路由纯粹是为了用户体验,而不是安全性。安全性是通过保护 api 来处理的。
| 归档时间: |
|
| 查看次数: |
1717 次 |
| 最近记录: |