gpt4 book ai didi

java - 如何允许 "/api/**"通过我的基本身份验证配置并进入 Spring Security 中的 oauth 配置

转载 作者:行者123 更新时间:2023-11-30 02:39:38 25 4
gpt4 key购买 nike

我有一个同时使用基本身份验证和 OAuth2 的应用。

某些 URL 使用基本身份验证进行授权,“/api/**”使用 OAuth2 进行授权。

目前,我有两个 Java 配置文件(WebSecurityConfigurerAdapterResourceServerConfigurerAdapter)

每个配置文件都定义一个 public void configure(HttpSecurity http) 方法。

我遇到的麻烦是,我需要一种优雅的方式来告诉我的应用程序在给定 url 请求的情况下是使用基本身份验证还是使用 oauth2。

目前我正在使用 requestMatchers 来实现这一点:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.csrf().disable()
.requestMatchers()
.antMatchers("/*", "/login/**", "/reviews/**")
.and()
.authorizeRequests()
.antMatchers("/*").permitAll()
.antMatchers("/js/**").permitAll()
.antMatchers("/img/**").permitAll()
.formLogin()
.loginPage("/login")
.successHandler(loginSuccessPostHandler)
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/").permitAll()
.and()
.apply(getSpringSocialConfigurer());
}
}

@Configuration
public class OAuth2ServerConfig
{
@Configuration
@EnableResourceServer
protected static class Oauth2ServerConfig extends ResourceServerConfigurerAdapter
{
@Override
public void configure(HttpSecurity http) throws Exception
{
http.httpBasic().disable();
http.csrf().disable();

http.requestMatchers()
.antMatchers("/api/**")
.and()
.authorizeRequests()
.antMatchers("/api/v1/**").access("#oauth2.hasScope('read')");
}
}
}

问题是,每次我添加一个不是“/api/**”的新 URL 时,我都需要将其添加到我的 WebSecurityConfig 的 requestMatcher 部分...这可能导致将来出现愚蠢的错误。

有没有办法根据负向前瞻正则表达式进行 requestMatcher 搜索?我使用正则表达式尝试了此操作: ^(?!/api) 但由于它实际上并不返回 MATCH 而只返回“find == true”,因此它似乎没有得到工作完成。

有什么想法/建议吗?

最佳答案

您可以使用NegatedRequestMatcher :

A RequestMatcher that will negate the RequestMatcher passed in. For example, if the RequestMatcher passed in returns true, NegatedRequestMatcher will return false. If the RequestMatcher passed in returns false, NegatedRequestMatcher will return true.

关于java - 如何允许 "/api/**"通过我的基本身份验证配置并进入 Spring Security 中的 oauth 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42121778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com