spring-boot - 每个 url 模式的身份验证提供程序 - Spring Boot
问题描述
在使用 Spring Boot 安全性为每个 url 模式配置不同的身份验证提供程序时,我遇到了问题。我正在尝试在 Spring Boot 应用程序中配置安全性,并希望在基本身份验证之后大摇大摆,并且所有 API 仅由令牌保护。我几乎可以使用它,但注意到 API 除了它由 IDAuthProvider 类验证的令牌保护之外,它还由基本身份验证保护。我不希望这样,并且还注意到如果我删除了 line:
sessionCreationPolicy(SessionCreationPolicy.STATELESS).
它似乎工作正常,但仍然在请求中添加了标头 Basic {token} 这是我不想要的......
你知道我该如何配置它使所有由基本身份验证保护的东西和由令牌保护的API东西保护的所有东西?
我的配置如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Configuration
@Order(1)
public class SwaggerSecurityConfig extends WebSecurityConfigurerAdapter {
private final AuthenticationProvider userPassAuthProvider;
@Autowired
SwaggerSecurityConfig(UserPassAuthProvider userPassAuthProvider) {
this.userPassAuthProvider = userPassAuthProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/swagger**").
authorizeRequests().
antMatchers("/swagger**").authenticated().
and().httpBasic().and().csrf().disable();
}
@Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(userPassAuthProvider);
}
}
@Configuration
@Order(2)
public class APISecurityConfig extends WebSecurityConfigurerAdapter {
private final AuthenticationProvider idAuthProvider;
@Autowired
APISecurityConfig(IDAuthProvider idAuthProvider) {
this.idAuthProvider = idAuthProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api/v1/**").
authorizeRequests().anyRequest().authenticated().
and().
addFilterBefore(idpAuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class).sessionManagement().
and().
csrf().disable();
}
@Override
public void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(idAuthProvider);
}
IDPAuthenticationFilter idpAuthenticationFilter(AuthenticationManager auth) {
return new IDPAuthenticationFilter(auth, new OrRequestMatcher(new AntPathRequestMatcher(ApiRouter.API_PATH + "/**", HttpMethod.GET.toString()), new AntPathRequestMatcher(ApiRouter.API_PATH + "/**", HttpMethod.POST.toString()), new AntPathRequestMatcher(ApiRouter.API_PATH + "/**", HttpMethod.DELETE.toString()), new AntPathRequestMatcher("/swagger**", HttpMethod.GET.toString())));
}
}
}
解决方案
推荐阅读
- amazon-web-services - 使用 Map 类型开始执行状态机
- python - python 是否无法识别我在 if 语句中使用的变量,该变量也用于 for 中?
- java - MongoRepository 查询日期是否在上周内
- python - 添加到文件时如何从字符串中删除''引号和方括号[]
- jmeter - JMeter - Web 报告 - 随时间变化的响应时间仅显示平均值
- javascript - 使用 jQuery 计时 css 动画循环
- sql - 使用 dbplyr 检查记录是否存在
- python - 是否可以将异步函数作为可调用参数?
- python - 无法让 pip 和 setuptools 同意
- c - 检测素数的 C 程序