java - 如何将 Spring Web 应用程序配置为每个端点使用不同的身份验证方法
问题描述
我有一个 Web 应用程序——使用 Java、Spring 和 Spring Security 构建——需要支持两种不同的身份验证方法。我遇到的困难是我想在一组控制器端点上使用一种身份验证方法,而在其余端点上使用另一种方法。
这是一个困难,因为我读过的有关多个身份验证提供程序的所有文档似乎都假设您希望所有提供程序都应用于所有端点,并且您遍历提供程序,直到找到一个可以对用户进行身份验证的提供程序。
我正在使用基于 Java 注释的配置(而不是 XML 配置)。以下是我探索但没有成功的一些方法:
- 使用模式匹配器配置提供程序以限制它应用的端点
- 将提供程序配置为仅针对某些身份验证类型触发,例如。如果存在摘要凭据,则触发基于摘要的身份验证提供程序
谁能建议解决此问题的最佳方法是什么?上述方法之一是正确的方法吗(我只是弄错了)?还是有另一种首选方式?
(我知道我没有提供具体的代码来审查某个问题。这是因为我只是在获得有关 Spring 中适当的做事方式的指导之后。)
解决方案
我正在使用 Spring Boot 2.0。我不知道最好的方法,但这是一种对我有用的方法。我不得不把它分解成单独的配置类,第二个配置需要在上面加上@Order注释。
对于我的特殊情况,我需要一些通过 HTTP 基本身份验证(用户名/密码)保护的管理 REST 方法,而其余的 REST 方法需要通过自定义逻辑来保护。
@Configuration
@EnableWebSecurity
public class TestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
// anything that is NOT /admin/**
RequestMatcher requestMatcher = new NegatedRequestMatcher(new AntPathRequestMatcher("/admin/**", "GET"));
// MyCustomFilter is my class that performs custom authentication logic
http.requestMatcher(requestMatcher)
.addFilterAfter(new MyCustomFilter(), BasicAuthenticationFilter.class);
}
@Order(1)
@Configuration
public static class AdminServiceConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//this time anything that IS /admin/**
http.requestMatchers()
.antMatchers("/admin/**").and()
.httpBasic().and()
.authorizeRequests().antMatchers("/admin/**").fullyAuthenticated();
}
@Override
protected void configure(AuthenticationManagerBuilder authBuilder) throws Exception {
authBuilder.inMemoryAuthentication()
.passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("username")
.password("password")
.roles("ADMIN");
}
}
}
推荐阅读
- excel - Excel 我可以手动添加列以查询和保留行完整性-链接-当原始表行数更改时?
- kubernetes - 您与此站点的连接不安全(nginx 入口)
- javascript - 如何对按钮进行缩放效果?
- android - 非静态方法 filterdList(ArrayList
) 不能从静态上下文中引用 - java - 读取 Blob 文件而不将其保存为文件
- javascript - 使用 Fetch 返回的 Promise 不响应 .then()
- python - 根据 Python 中第二个列表中的值从第一个列表中复制项目
- php - 如何将默认子数组值应用于关联多维数组?
- node.js - 如何使用 gcloud compute nodejs 客户端分配 serviceAccount?
- jquery - 问题:打开后立即关闭窗口的Jquery打印