Java Spring @EnableResourceServer и @EnableWebSecurity - PullRequest
0 голосов
/ 11 мая 2018

У меня есть RESTful сервер ресурсов Spring с @EnableResourceServer и расширением ResourceServerConfigurerAdapter

В документации написано:

... Чтобы использовать этот фильтр, вы должны @EnableWebSecurity где-то в вашем приложении, либо там же, где вы используете эту аннотацию, либо где-то еще.

Но когда я добираюсь до public @interface EnableResourceServer, я вижу ResourceServerConfiguration extends WebSecurityConfigurerAdapter.

Вопрос: Так что мне нужно для чистого RESTful API?

  1. @EnableWebSecurity на любом @Config
  2. Расширить WebSecurityConfigurerAdapter?
  3. 1 + 2
  4. Ни

Мой конфиг

@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();
    }
}

Ответы [ 2 ]

0 голосов
/ 11 мая 2018

Spring Boot делает @EnableWebSecurtiy неявным , но в противном случае это необходимо.

Вы можете убедиться в этом сами, взглянув на этот пример сервера ресурсов OAuth2 .Если вы удалите аннотацию @EnableWebSecurity, вы обнаружите, что цепь фильтра безопасности Spring не подключена.

Вы все еще можете расширить WebSecurityConfigurerAdapter, чтобы отделить общие проблемы безопасности веб-приложений от тех, которые относятся к конфигурации сервера ресурсов.,Это не является технически необходимым, но может сделать для более четкое разделение проблем .

0 голосов
/ 11 мая 2018

Нет, включение EnableWebSecurity неявное.

Я не рекомендую использовать WebSecurityConfigurerAdapter, у вас возникнут некоторые проблемы: Правильно настройте безопасность пружины oauth2

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...