【发布时间】:2023-04-02 09:20:01
【问题描述】:
我有一个带有 OAuth2 授权的 Spring Cloud 应用程序:
@RestController
@RequestMapping("/product")
public class ProductController {
@GetMapping("/categories")
public ResponseEntity<Map<Integer, CategoryFullDTO>> getCategoriesList() {
.......
}
}
我添加了这个安全配置:
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(final HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.POST, "/oauth/token").permitAll()
.antMatchers(HttpMethod.GET, "/product/categories").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic().disable()
.formLogin()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
.and().csrf().disable();
}
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.POST, "/oauth/token").permitAll()
.antMatchers(HttpMethod.GET, "/product/categories").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic().disable()
.formLogin()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
.and().csrf().disable();
// http.requiresChannel()
// .anyRequest().requiresInsecure();
}
}
当我打开 Angular 应用程序时出现访问错误:Failed to load resource: the server responded with a status of 401 () for /product/categories
您知道我需要应用什么配置才能在没有强制授权的情况下公开此路径吗?
P.S 当我使用 Postman 发出请求时,它正在工作。它确实在未经授权的情况下返回数据。但是看起来如果您仍然存在 auth_token 并且它已经过期,似乎我的授权拦截器仍然捕获它并将其应用于导致错误的请求。 看起来 JWT 令牌验证逻辑返回错误。我该如何解决这个问题?
【问题讨论】:
-
你试过像
web.ignoring().antMatchers("/product/categories")这样的配置吗? -
查看上面的答案,它解释了您的需求解决方案。但是,通常前端应用程序应该有一个 API 调用拦截器,它应该刷新令牌或在授权错误时重定向到登录页面。
标签: spring spring-boot spring-security-oauth2 spring-oauth2