Spring 安全性正在阻止 Vue.js 个页面 |收到 403 错误

Spring security is blocking Vue.js pages | receiving 403 error

我有一个 Spring/Vuejs 项目,它将前端和后端耦合到一个 warFile 中,出于某种原因,我的 Spring 安全设置在我 运行 warFile.

当我以这种方式设置配置时,它会阻止页面 -

@Override
public void configure(HttpSecurity security) throws Exception {
    security.csrf().disable()
            .cors().and()
            .authorizeRequests()
            .antMatchers("/api/v1/authenticate", "/api/v1/register").permitAll()
            .anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    security.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

当我以这种方式设置它时,它会显示来自我的 api 的页面和数据(它创建了 JWT,但仍然允许 api 未经授权的调用)-

@Override
public void configure(HttpSecurity security) throws Exception {
    security.csrf().disable()
            .cors().and()
            .authorizeRequests()
            .antMatchers("/api/v1/authenticate", "/api/v1/register", "/**","/css/**","/js/**").permitAll()
            .anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    security.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

当我以第一种方式设置它并且 运行 在不同端口上设置前端和后端时,它工作得很好。它显示页面并阻止所有 API 没有授权 JWT 的调用。

我想在同一个 warFile

中得到与 backend/frontend 相同类型的结果

有解决办法吗???

When I have it setup the first way and run the frontend and backend on different ports, it works perfectly.

请问是不是调用了CORS策略。否则,Spring 安全部门在做出授权决定时不会考虑端口号。

When I have the Configuration set this way, it blocks the pages -

那是因为你有这条线:

.anyRequest().authenticated()

这意味着任何URL,包括JS文件,都需要验证。

When I have it set up this way, it shows the pages AND the data from my api's

那是因为你有这条线:

.antMatchers("/**").permitAll()

表示允许任意URL

DSL 处理 URL 秒 in the order the paths are declared。我想你想要两者的混合体。像这样:

.antMatchers("/api/v1/authenticate", "/api/v1/register", "/css/**","/js/**").permitAll()
.anyRequest().authenticated()

这意味着两个 /api 端点所有 /css 个端点和所有 /js 个端点不需要身份验证,但其他所有端点都需要。

考虑尽可能缩小 permitAll -- 我不清楚您是否真的希望所有 JS 文件都不需要身份验证。

@jzheaux 你的根评论让我找到了答案。

这是我所做的更改,它可以正常工作,正如我现在需要的那样。感谢指导!

@Override
public void configure(HttpSecurity security) throws Exception {
    security.csrf().disable()
            .cors().and()
            .authorizeRequests()
            .antMatchers("/api/v1/authenticate","/api/v1/register","/static/**","/").permitAll()
            .anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    security.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}