且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring针对不同api端点的多种身份验证方法

更新时间:2023-12-01 08:38:28

您有两个过滤器链.它们都没有正确配置的入口点模式 http.antMatcher.这意味着它们被配置为使用 /** 作为它们的入口点模式.

You have two filter chains. Neither of them have an entry point pattern properly configured http.antMatcher. That means they are configured to use /** as their entry point pattern.

例如

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().fullyAuthenticated()

就是说:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .antMatcher("/**")
            .authorizeRequests()
                .anyRequest().fullyAuthenticated()

我们在这里说的是

  1. http - 安全过滤器链
  2. http.antMatcher - 安全过滤器链的入口点
  3. http.authorizeRequests - 我的端点访问限制的开始
  4. http.authorizeRequests.antMatchers - 具有特定访问权限的 URL 列表
  1. http - the security filter chain
  2. http.antMatcher - the entry point to the security filter chain
  3. http.authorizeRequests - start of my endpoint access restrictions
  4. http.authorizeRequests.antMatchers - list of URLs with specific access

所以您需要做的是更改您的 @Order(1) 过滤器链以缩小模式.例如:http.antMatcher("/api/transaction/**")

So what you need to do is change your @Order(1) filter chain to narrow down the pattern. For example: http.antMatcher("/api/transaction/**")

您的配置现在看起来像


    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/api/transaction/**") //customized entry point
                .authorizeRequests()
                .antMatchers("/api/transaction/testf").authenticated().and()
                .x509()
                .subjectPrincipalRegex("CN=(.*?)(?:,|$)")
                .userDetailsService(new X509UserDetailsService())
                ;
        }
    }

    @Configuration
    @Order(2)
    public static class ApiTokenSecurityConfig extends WebSecurityConfigurerAdapter{

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/**") //this is default
                .authorizeRequests()
                .antMatchers("/oauth/token", "/api/dealer/login").permitAll()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                ;
        }

使用您现有的配置,名为 ApiWebSecurityConfig 的过滤器链将捕获所有调用.另一个过滤器链 ApiTokenSecurityConfig 从未使用过.

With your existing configuration the filter chain named ApiWebSecurityConfig will trap all calls. The other filter chain, ApiTokenSecurityConfig, is never used.

你可以在这个答案

SpringSecurity:制作仅通过单个端点即可实现 RESTful API 基本身份验证