java - 带有路径变量的 Spring Boot AuthenticationToken
问题描述
我有PreAuthenticatedProcessingFilter
一个自定义项AuthenticationManager
,我在其中进行身份验证并创建一个 AuthenticationToken
. 我现在需要访问一个路径变量(例如“/foo/{id}”的 id)并将其用于我的身份验证。我如何访问变量?例如,如果我使用.antMatchers("/foo/{id}").access("@demo.check(authentication,#id)");
我无法创建自己的令牌。
我当前的代码是:
MyAuthFilter filter = MyAuthFilter();
filter.setAuthenticationManager(new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// ... authentication stuff
// here i want to access the path variable
return new MyAuthenticationToken(foo);
}
});
httpSecurity.antMatcher("/foo/**").csrf().disable().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().addFilter(filter).authorizeRequests().anyRequest().authenticated();
更新
我现在正在检查访问表达式中的所有内容(您可以在那里访问 HttpServletRequest 并将路径变量作为参数)。我不想在控制器中有逻辑或检查原始路径。所以这对我来说现在很好:
httpSecurity.antMatcher("/foo/**").csrf().disable().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.antMatchers("/foo/test/{testId}/**")
.access("@fooApiGuard.check(authentication, #testId)");
@Service
public class FooApiGuard {
@Autowired
private HttpServletRequest request;
public boolean check(Authentication authentication, Long testId) throws AuthenticationException {
// check stuff
return true;
}
}
解决方案
Spring Security 构建为过滤器链,这意味着在您的自定义过滤器内部,或者AuthenticationManager
您没有与控制器方法本身内部完全相同的上下文。实际上,您的自定义过滤器应该增加您的控制器将使用的上下文。
您可以访问的是ServletRequest
andServletResponse
对象,因此如果必须,您可以从中提取原始路径。但是,这并没有为您提供很好分离的请求参数。
如果路径参数仅用于确定某人是否被授权,那么您可以简化您的身份验证逻辑,然后通过额外的安全检查来增加您的控制器,以验证例如域级别的安全问题(资源是否属于当前用户)。
推荐阅读
- java - 编辑打开的 .txt 中的文件并用 Java 中的新数据替换它们的过程
- discord - 在 Discord JS (v12) 上发送一条消息
- apache-kafka - 使用 SeekToCurrentErrorHandler 时,多个服务实例中同一消费者组中的同一消费者如何工作
- android - 离线 Gradle 构建失败
- typescript - 如何测试 iframe 并获取所有响应标头?
- r - 如何停止从 rstudio 中的标准输入获取输入
- java - 如何在 Apache Camel 中使用 Oauth 标头调用 REST API?
- ios - 带有在 IB 中创建的自定义视图的 InputAccessoryView
- neo4j - Neo4j-Spring-Data 深度功能不适用于丰富的关系
- grails - Grails:在一个视图中引用两个模型