首页 > 解决方案 > 如何将 Spring Web 应用程序配置为每个端点使用不同的身份验证方法

问题描述

我有一个 Web 应用程序——使用 Java、Spring 和 Spring Security 构建——需要支持两种不同的身份验证方法。我遇到的困难是我想在一组控制器端点上使用一种身份验证方法,而在其余端点上使用另一种方法。

这是一个困难,因为我读过的有关多个身份验证提供程序的所有文档似乎都假设您希望所有提供程序都应用于所有端点,并且您遍历提供程序,直到找到一个可以对用户进行身份验证的提供程序。

我正在使用基于 Java 注释的配置(而不是 XML 配置)。以下是我探索但没有成功的一些方法:

谁能建议解决此问题的最佳方法是什么?上述方法之一是正确的方法吗(我只是弄错了)?还是有另一种首选方式?

(我知道我没有提供具体的代码来审查某个问题。这是因为我只是在获得有关 Spring 中适当的做事方式的指导之后。)

标签: javaspringspring-mvcspring-security

解决方案


我正在使用 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");
        }
    }
}

推荐阅读