Spring Boot:对无状态REST API和有状态API进行身份验证;“登录”;同一项目中的Web控制器?

Spring Boot:对无状态REST API和有状态API进行身份验证;“登录”;同一项目中的Web控制器?,spring,spring-boot,spring-security,Spring,Spring Boot,Spring Security,因此,我有一个包含RESTAPI的应用程序,该应用程序由IOT设备上的定制java应用程序使用,无需用户交互。我还有一个web应用程序,它需要一个有状态会话来维护用户登录 是否可以使用Spring Security以不同的方式对发送到my API和web controller的请求进行身份验证?REST API应该使用何种形式的身份验证?实现所需功能的一种方法是在Spring Security中使用两种配置。例如 注意antMatcher(matcher不匹配s)。antMatcher将控制整个

因此,我有一个包含RESTAPI的应用程序,该应用程序由IOT设备上的定制java应用程序使用,无需用户交互。我还有一个web应用程序,它需要一个有状态会话来维护用户登录


是否可以使用Spring Security以不同的方式对发送到my API和web controller的请求进行身份验证?REST API应该使用何种形式的身份验证?

实现所需功能的一种方法是在Spring Security中使用两种配置。例如

注意
antMatcher
matcher不匹配s)。
antMatcher
将控制整个配置所应用的url集,即下例中的
FormLoginWebSecurityConfigureAdapter
将仅应用于uri匹配
/api/test/**
。当然,您只能在其中一个配置中定义
antMatcher
,比如说config1,在这种情况下,另一个配置将是一个全面捕获(即捕获与config1不匹配的所有内容)


您希望以有状态和无状态的方式访问相同的RESTURL。或者你说的是有状态和无状态共存,每一个都用于不同的URL集?如果你想有状态和无状态共存,每一个都用于不同的URL集,请看我下面的答案。对不同的URL是
@EnableWebSecurity
@Configuration
public class SecurityConfig {


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

        @Override       
        public void configure(AuthenticationManagerBuilder auth) 
          throws Exception {            
            auth.inMemoryAuthentication().withUser("user").password("user").roles("USER");
            auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
        }

        protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

            http
                .antMatcher("/api/v1/**")                               
                .authorizeRequests()
                .antMatchers("/api/v1/**").authenticated()
                    .and()
                .httpBasic();
        }
    }

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

        @Override       
        public void configure(AuthenticationManagerBuilder auth) 
          throws Exception {

            auth.inMemoryAuthentication().withUser("user1").password("user").roles("USER");
            auth.inMemoryAuthentication().withUser("admin1").password("admin").roles("ADMIN");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED); // CONFIGURE TYPE OF SESSION POLICY
            http
                .antMatcher("/api/test/**")
                .authorizeRequests()
                .antMatchers("/api/test/**").authenticated()
                    .and()
                .formLogin();
        }
    }
}