您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring Boot:在同一项目中同时验证无状态REST API和有状态“登录” Web控制器?

Spring Boot:在同一项目中同时验证无状态REST API和有状态“登录” Web控制器?

实现您所寻找的一种方法是在Spring Security中具有2种配置。例如

注重antMatcher( 不匹配 )。在antMatcher将控制在什么网址设置您的整个配置适用即formLoginWebSecurityConfigurerAdapter在下面的例子将仅适用于URI匹配/api/test/**。当然,您可以antMatcher在其中一个配置中定义唯一的名称,即config1,在这种情况下,另一个配置将是全部捕获(即,捕获与config1不匹配的所有内容

@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();
        }
    }
}
Java 2022/1/1 18:17:01 有502人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶