【问题标题】:spring security work only for highest priority order [duplicate]春季安全仅适用于最高优先级订单[重复]
【发布时间】:2019-10-01 21:08:53
【问题描述】:

我正在尝试将 spring mvc 集成到现有的 spring rest 项目中。春季休息的安全工作正常。当我尝试以最低优先级顺序为 spring mvc 实现安全性时,它仅适用于 rest api。如果我为 spring mvc 设置了高优先级,那么它将适用于 spring mvc,但对于 rest api,它将重定向到登录页面。

这是我的代码 sn-p

//base class for spring security config
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig 

我有两个静态类

对于spring mvc

@Configuration
@EnableWebSecurity
@Order(1)
public static class SecurityConfig extends WebSecurityConfigurerAdapter

用于休息 api

@Configuration
@EnableWebSecurity
@Order(2)
public static class ApiSecurity extends WebSecurityConfigurerAdapter

对于spring mvc配置

@Override
protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/resources/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/admin/login")
                .defaultSuccessUrl("/admin/home",true)

                .permitAll()
                .and()
                .logout()
                .permitAll();
}

用于Rest api配置

@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors()
                .and()
                // we don't need CSRF because our token is invulnerable
                .csrf().disable()

                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

                // don't create session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

                .authorizeRequests()

                // Un-secure H2 Database
                .antMatchers("/h2-console/**/**").permitAll()

                .antMatchers("/auth/**").permitAll()
                .antMatchers("/refresh/**").permitAll()

                .antMatchers("/facebook/**").permitAll()
                .antMatchers("/admin/**").permitAll()
                .antMatchers("/v2/api-docs",
                        "/configuration/ui",
                        "/swagger-resources",
                        "/configuration/security",
                        "/swagger-ui.html").permitAll()
                .anyRequest().authenticated();

        // Custom JWT based security filter
        JwtAuthorizationTokenFilter authenticationTokenFilter = new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);
        httpSecurity
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // disable page caching
        httpSecurity
                .headers()
                .frameOptions().sameOrigin()  // required to set for H2 else H2 Console will be blank.
                .cacheControl();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // AuthenticationTokenFilter will ignore the below paths
        web
                .ignoring()
                .antMatchers(
                        HttpMethod.POST,
                        authenticationPath)
                .antMatchers(HttpMethod.POST,
                        refresh)
                // allow anonymous resource requests
                .and()
                .ignoring()
                .antMatchers(
                        HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/*.js",
                        "/*.*.*",
                        "/**/**/*.*",
                        "/favicon.ico",
                        "/v2/api-docs",
                        "/configuration/ui",
                        "/swagger-resources",
                        "/configuration/security",
                        "/swagger-ui.html",
                        "/resources/**",
                        "/static/**"
                )

                // Un-secure H2 Database (for testing purposes, H2 console shouldn't be unprotected in production)
                .and()
                .ignoring()
                .antMatchers("/h2-console/**/**");
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
}

【问题讨论】:

    标签: java spring spring-boot spring-security


    【解决方案1】:

    每个WebSecurityConfigurerAdapter基本上都配置一个SecurityFilterChain,默认会处理所有的HTTP请求。

    当有多个SecurityFilterChain时,它会按照优先级顺序逐个检查每个SecurityFilterChain,并使用能处理请求的第一个。

    由于SecurityFilterChain 都配置为处理所有HTTP 请求,因此始终使用优先级较高的SecurityFilterChain

    因此,只需将 API 的 SecurityFilterChain 更改为具有更高优先级,并将其配置为处理以 API 端点开头的 URL:

    @Configuration
    @EnableWebSecurity
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public static class ApiSecurity extends WebSecurityConfigurerAdapter{
    
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http.antMatcher("/api/**");
                //continue configure http ......
            }
    
    }
    

    【讨论】:

    • \@EnableWebSecurity 已经包含了\@Configuration
    猜你喜欢
    • 2012-10-27
    • 2013-12-22
    • 2017-09-19
    • 2016-08-24
    • 1970-01-01
    • 2014-02-02
    • 2012-12-13
    相关资源
    最近更新 更多