首页 > 解决方案 > 带有路径变量的 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;
    }
}

标签: javaspringspring-bootsecurity

解决方案


Spring Security 构建为过滤器链,这意味着在您的自定义过滤器内部,或者AuthenticationManager您没有与控制器方法本身内部完全相同的上下文。实际上,您的自定义过滤器应该增加您的控制器将使用的上下文。

您可以访问的是ServletRequestandServletResponse对象,因此如果必须,您可以从中提取原始路径。但是,这并没有为您提供很好分离的请求参数。

如果路径参数仅用于确定某人是否被授权,那么您可以简化您的身份验证逻辑,然后通过额外的安全检查来增加您的控制器,以验证例如域级别的安全问题(资源是否属于当前用户)。


推荐阅读