如何为两个不同的端点设置两种不同的身份验证?

y53ybaqx  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(179)

我的第一个问题是:我有一个spring启动应用程序,在控制器中有两个URL,需要它们使用两种不同的身份验证,一种是oauth 2,另一种是api密钥验证。
它们单独工作,但当我放入一个安全配置时,顺序1 oauth工作,但顺序2 api密钥不工作:

@Configuration
@EnableWebSecurity
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

        @Autowired
        AuthenticationManagerResolver authenticationManagerResolver;

        @Autowired
        IdentityConfig theIdentityConfig;

        @Override
        public void configure(WebSecurity web) throws Exception {
            IdentityHelper.defaultWebConfig(web, theIdentityConfig);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            IdentityHelper.defaultHTTPConfig(http, theIdentityConfig);
        }
    }

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            ApiKeyAuthFilter filter = new ApiKeyAuthFilter("API_KEY");
            filter.setAuthenticationManager(new ApiKeyAuthManager());

            http
                .antMatcher("/endpoint2/apikey")
                .csrf().disable()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                .addFilter(filter)
                .authorizeRequests()
                    .anyRequest().authenticated();
        }
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题