首页 > 解决方案 > 我们能否根据 Mediatype 加载不同的安全配置,即一种 REST 和一种用于 Web?

问题描述

我已经开发了一个常规的 spring mvc 应用程序,并且想添加一些用于开发移动应用程序的 rest 控制器。我已经编写了休息控制器和多弹簧安全配置。

问题是,它们是优先的,因此两者都同时加载,整个应用程序都崩溃了。我想根据它收到的请求类型来使用一个,例如,如果我从 Postman 请求,Rest API 安全配置应该可以工作,如果我们使用网络,网络安全配置应该可以工作。

这是我的实现,我不知道如何实现,请提出正确的方法。由于分离整个 Thymeleaf 和 MVC 控制器,并且在这个阶段完全与 Angular 一起移动是不可能的。

请注意,我们在/v1/ap1/ ** 中定义了所有 rest api,所有其他 mvc 部分都在 / **

任何意见、建议将不胜感激,因为 3 天以来我的日子都快要死了。提前致谢

@Configuration
@EnableWebSecurity
public class SecurityConfig {
     // ... other codes
     @Configuration
     @Order(1)
     public static class RestAPISecurity extends WebSecurityConfigurerAdapter {
       //.. other codes
       protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/api/signin/**").permitAll()
                .antMatchers("/api/v1/**").hasAnyAuthority("ADMIN", "USER")
                .antMatchers("/api/users/**").hasAuthority("ADMIN")
                .antMatchers("/api/v1/**").authenticated()
                .antMatchers("/login", "/logout", "/register", "/j_spring_security_check").permitAll()
                .anyRequest().authenticated()
                .and().exceptionHandling().authenticationEntryPoint(customAuthenticationEntryPoint).accessDeniedHandler(new CustomAccessDeniedHandler());
    }
// .. other codes
    @Configuration
    @Order(2)
    public static class MVCSecurityConfiguration extends WebSecurityConfigurerAdapter {
        //.. other codes
        // form login and other MVC stuffs
    }
}

标签: springspring-bootspring-mvcspring-securityspring-security-oauth2

解决方案


您可以为第一个 spring 安全过滤器链添加请求匹配器,其他所有内容都转到第二个链

    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(httpServletRequest -> {
              String userAgent = httpServletRequest.getHeader("User-Agent");      
              //If you want to check based on content type
              String contentType = httpServletRequest.getContentType();

              return userAgent.contains("....")
              //check what value postman sends as user agent and use it
            })
            .sessionManagement()
            ....
    }

推荐阅读