java Spring @EnableResourceServer和@EnableWebSecurity

时间:2018-05-11 14:13:27

标签: java spring spring-boot spring-security spring-security-oauth2

我的{strong> RESTful Spring资源服务器@EnableResourceServer并扩展ResourceServerConfigurerAdapter

documentations中说:

  

...为了使用这个过滤器,你必须在应用程序的某个地方使用@EnableWebSecurity,或者在你使用这个注释的地方或其他地方。

但当我到public @interface EnableResourceServer时,我看到ResourceServerConfiguration extends WebSecurityConfigurerAdapter

问题: 那么纯RESTful API需要什么呢?

    任何@EnableWebSecurity 上的
  1. @Config
  2. 扩展WebSecurityConfigurerAdapter
  3. 1 + 2
  4. 既不
  5. 我的配置

    @Configuration
    @EnableResourceServer
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class HGResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {
    
        @Override
        public void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity
            .cors().disable()
            .csrf().disable()
            .formLogin().disable()
            .httpBasic().disable()
            .jee().disable()
            .logout().disable()
            .rememberMe().disable()
            .servletApi().disable()
            .x509().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and().authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .and().authorizeRequests().antMatchers(Url.API_ERROR_LOGS_FRONTEND).permitAll()
            .and().authorizeRequests().antMatchers(Url.API_REGISTER_PATH).permitAll()
            .and().authorizeRequests().antMatchers(Url.API_VERIFY_EMAIL_PATH).permitAll()
            .and().authorizeRequests().antMatchers(Url.API_RESET_PASSWORD_PATH).permitAll()
            .and().authorizeRequests().antMatchers(Url.API_CONFIRM_RESET_PASSWORD_PATH).permitAll()
            .and().authorizeRequests().anyRequest().authenticated();
        }
    
        @Primary
        @Bean
        public RemoteTokenServices tokenService() {
            RemoteTokenServices tokenService = new RemoteTokenServices();
            tokenService.setCheckTokenEndpointUrl("http://localhost:8081/oauth/check_token");
            tokenService.setClientId("client");
            tokenService.setClientSecret("secret");
            return tokenService;
        }
    
    
        //disable default user creation
        @Bean
        public UserDetailsService userDetailsService() throws Exception {
            return new InMemoryUserDetailsManager();
        }
    
        //password encoder
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }
    

1 个答案:

答案 0 :(得分:1)

Spring Boot makes @EnableWebSecurtiy implicit,但不是必需的。

您可以通过查看OAuth2 resource server example来证明这一点。如果删除那里的@EnableWebSecurity注释,您会发现Spring Security Filter Chain没有连线。

您仍然可以将WebSecurityConfigurerAdapter扩展为将特定于资源服务器配置的常规Web应用程序安全问题分开。这在技术上是不必要的,但可以用于a cleaner separation of concerns