Использование WebSecurityConfigurerAdapter с Spring OAuth2 и user-info-uri

Я создал службу авторизации следующим образом

@SpringBootApplication
@EnableAuthorizationServer
public class AuthorizationApplication {
   ...
}

С этим application.properties.

server.port=9000
security.oauth2.client.client-id=monederobingo
security.oauth2.client.client-secret=monederobingosecret
security.oauth2.client.authorized-grant-types=authorization_code,refresh_token,password,client_credentials
security.oauth2.client.scope=company,client

Затем в отдельном проекте весенней загрузки я создал сервер ресурсов.

@SpringBootApplication
@EnableResourceServer
public class App {
   ...
}

С этим application.properties.

server.port=9090
spring.application.name=app
security.oauth2.resource.user-info-uri=http://localhost:9000/user

Теперь все работает нормально, если я отправлю такой запрос localhost:9090/api с соответствующим токеном, который был получен службой авторизации.

Однако я не хочу отправлять этот токен при отправке запросов на localhost:9090/login.

Для этого я создал этот класс в своем весеннем загрузочном приложении сервера ресурсов.

@Configuration
public class SpringConfig extends WebSecurityConfigurerAdapter {
    @Override protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/login")
                .permitAll()
                .antMatchers("/api/**")
                .authenticated();
    }

}

И теперь мне не нужно отправлять какой-либо токен, чтобы отправить запрос на /login.

Однако теперь я получаю следующее сообщение при отправке запроса на /api с действительным токеном.

{
  "timestamp": 1496027102659,
  "status": 403,
  "error": "Forbidden",
  "message": "Access Denied",
  "path": "/api/v1/points_configuration/314"
}

Как настроить безопасность только для нескольких шаблонов URL-адресов в Spring Security OAuth2?


person alayor    schedule 29.05.2017    source источник
comment
Добавьте .antMatchers(/api/**) .authenticated(); в конфигурации вашего сервера ресурсов и повторите попытку   -  person Afridi    schedule 29.05.2017
comment
@Afridi У меня уже есть это в SpringConfig классе.   -  person alayor    schedule 29.05.2017
comment
Я не говорю о расширенном классе WebSecurityConfigurerAdapter. Расширяет ваш класс App из ResourceServerConfigurerAdapter, а затем переопределяет этот метод: }   -  person Afridi    schedule 29.05.2017
comment
@ Это сработало. Не могли бы вы добавить это как ответ, и я отмечу его как принятый. Кроме того, почему это сработало при использовании ResourceServerConfigurerAdapter вместо WebSecurityConfigurerAdapter?   -  person alayor    schedule 29.05.2017


Ответы (1)


Дополнительную информацию о безопасности Spring OAuth см. здесь:Защита Spring REST API с OAuth

Чтобы реализовать безопасность OAuth при загрузке Spring, вам необходимо создать сервер авторизации и ресурсов, расширив их от AuthorizationServerConfigurerAdapter и ResourceServerConfigurerAdapter соответственно.

Сервер авторизации

    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationApplication extends AuthorizationServerConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
                throws Exception {
            endpoints
                    .userDetailsService(userDetailsService)
                    .authenticationManager(this.authenticationManager).tokenStore(tokenStore()).approvalStoreDisabled();
        }

       @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.withClientDetails(mongoClientDetailsService);
            /*inMemory()
                    .withClient(propertyResolver.getProperty(PROP_CLIENTID))
                    .scopes("read", "write")
                    .authorities("ROLE_CLIENT")
                    .authorizedGrantTypes("password", "refresh_token","client_credentials")
                    .secret(propertyResolver.getProperty(PROP_SECRET))
                    .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 18000));*/
        }

//Do others stuff
    }

Сервер ресурсов

Все URL-адреса, которые вы хотите защитить с помощью OAuth, должны быть упомянуты в этой конфигурации сервера. Он включает фильтр Spring Security, который аутентифицирует запросы с использованием входящего токена OAuth2. В то время как в основном расширенный класс WebSecurityConfigurerAdapter используется для базовой настройки безопасности, такой как добавление фильтров, разрешение небезопасных URL-адресов или реализация политик сеанса и т. д.

@Configuration
@EnableResourceServer
public class App extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
    http.requestMatchers().antMatchers("/api/**").and().authorizeRequests()
                .antMatchers("/api/**").authenticated();
}
  //Do others stuff
}
person Afridi    schedule 30.05.2017
comment
userDetailsService(userDetailsService) недоступен в AuthorizationServerConfigurerAdapter - person wildthing81; 30.04.2018
comment
@wildthing81 Я использовал AuthorizationServerEndpointsConfigurer.userDetailsService(userDetailsService), а не AuthorizationServerConfigurerAdapter.** endpoints.userDetailsService(userDetailsService)... - person Afridi; 30.04.2018
comment
мой плохой... Я имел в виду Конфигуратор конечных точек сервера авторизации. метод не существует - person wildthing81; 30.04.2018
comment
Это помогает мне. Спасибо - person V-Q-A NGUYEN; 31.10.2018