Можем ли мы использовать httpbasic и OAuth2 для API в зависимости от переменной пути? - PullRequest
0 голосов
/ 11 июня 2018

В моем приложении я хочу обеспечить безопасность OAuth2 только для некоторых определенных вызовов API.У меня вопрос: могу ли я предоставить аутентификацию HttpBasic или Oauth2 на основе переменной пути?

Ниже приведены два сценария, которые я рассмотрю.

1) Скажем, для пользователя (имя которого указано в путипеременная) xyz, если xyz не имеет функции OAuth, я хочу аутентифицировать ее с помощью httpBasic

2) Если другой пользователь abc имеет функцию OAuth, я хочу аутентифицировать ее с помощью Oauth / OpenId connect.

У меня есть таблица, которая присваивает функции пользователю, ниже приведен проблеск таблицы.

Имя, функция

xyz, HttpBasic

abc, Oauth

1 Ответ

0 голосов
/ 15 июня 2018

Хорошо, я провел собственное исследование и смог найти решение.Вот что я сделал,

-Создал одну конфигурацию httpbasic с WebSecurityConfigurerAdapter, теперь, прежде чем любой перехватчик начинает его задачу, я создал один механизм сопоставления запросов, который будет проверять, является ли заголовок авторизации Basic или Bearer.

      //By default this filter order is 100 and OAuth has filter order 3
      @Order(2)
    public class MicroserviceSecurityConfigurationHttpBasic extends  WebSecurityConfigurerAdapter { 
          @Override
          protected void configure(HttpSecurity http) throws Exception {
             http.csrf().disable().exceptionHandling()
            .authenticationEntryPoint(customAccessDeniedHandler())
            .and().headers().frameOptions().disable()
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .requestMatcher(new BasicRequestMatcher())
            .authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .and().httpBasic();

          }
          private class BasicRequestMatcher implements RequestMatcher {
            @Override
            public boolean matches(HttpServletRequest httpRequest) {
             String auth = httpRequest.getHeader("Authorization");
             String requestUri = httpRequest.getRequestURI();
             //Fetching Identifier to provide OAuth Security to only specific urls
             String identifier= requestUri.substring(requestUri.lastIndexOf("/") + 1, requestUri.length());

            //Lets say for identifier ABC only, I want to secure it using OAuth2.0
           if (auth != null && auth.startsWith("Basic") && identifier.equalsIgnoreCase("ABC")) {
             auth=null;
              }
           //For ABC identifier this method will return null so then the authentication will be redirected to OAuth2.0 config.
           return (auth != null && auth.startsWith("Basic"));
            }
        }
  }

-После этого я создал конфигурацию OAuth2.0 с ResourceServerConfigurerAdapter, вот ее пример.

    //Default filter order=3 so this will be executed after WebSecurityConfigurerAdapter 
    public class MicroserviceSecurityConfiguration extends ResourceServerConfigurerAdapter {
       ...
      //Here I am intercepting the same url but the config will look for bearer token only
      @Override
public void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().exceptionHandling()
    .and().headers().frameOptions().disable()
    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
    .and().authorizeRequests()
    .antMatchers("/api/**").authenticated();
    }
   }

Ссылки: https://github.com/spring-projects/spring-security-oauth/issues/1024

Безопасность Spring с аутентификацией Oauth2 или Http-Basic для одного и того же ресурса

...