Отказано в доступе к серверу авторизации OAUTH2.0 "/ oauth / authorize" api - PullRequest
0 голосов
/ 05 апреля 2019

Я разрабатываю несколько микросервисов, которые взаимодействуют друг с другом для достижения определенных функциональных возможностей. Сейчас пытаюсь защитить эти микросервисы с помощью пружинной защиты со стандартом OAuth2.0. Я использую токены на основе JWT для аутентификации и простой собственный сервер аутентификации. Эти микросервисывзаимодействовать через общий шлюз (Netflix ZUUL) и пытаться в нисходящем направлении (распространение заголовка авторизации при взаимодействии одной микросервисной службы) с заголовком авторизации через шлюз @ EnableAuth2sso.

Теперь я пытаюсь подключиться к одному из моих защищенных микросервисов изПочтальон через шлюз Zuul (SSo включен). Успешно получил токен JWT с моего сервера авторизации.

Снимок экрана PostMan:

Получены токены JWT

, но когда я пытаюсь подключиться к моей защищенной службе через шлюз с помощью jwt token.its, выбрасывающего приведенное ниже исключение «Отказано в доступе».

Исключение Когда я пытаюсь подключиться к моей службе через шлюз

Доступ запрещен Исключение, когда я пытаюсь подключиться к моей защищенной службе ресурсов через шлюз

Вот мои коды

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

Реализация AuthorizationServerConfigurerAdapter:

@Configuration
@EnableAuthorizationServer
public class O2AuthServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    AuthenticationManager authManager;

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    TokenEnhancer tokenEnhancer;

    @Autowired
    JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    TokenStore tokenStore;
    /*
     * @Override public void configure(AuthorizationServerEndpointsConfigurer
     * endpoints) throws Exception {
     * 
     * endpoints.authenticationManager(authManager);
     * endpoints.userDetailsService(userDetailsService); }
     */

    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        TokenEnhancerChain enhancer = new TokenEnhancerChain();
        enhancer.setTokenEnhancers(Arrays.asList(tokenEnhancer, jwtAccessTokenConverter));
        endpoints.tokenStore(tokenStore);
        endpoints.tokenEnhancer(enhancer);
        endpoints.authenticationManager(authManager);
        endpoints.userDetailsService(userDetailsService);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("MyActiveClient").secret("{noop}activate")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
                .scopes("read");
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("isAuthenticated()").tokenKeyAccess("permitAll()");
    }

}

Реализация WebSecurityConfigurerAdapter:

   @EnableWebSecurity
@Configuration
public class O2AuthSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        // TODO Auto-generated method stub
        return super.authenticationManagerBean();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
        // TODO Auto-generated method stub
        return super.userDetailsServiceBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    PasswordEncoder encoder=PasswordEncoderFactories.createDelegatingPasswordEncoder(); 
    auth.inMemoryAuthentication()
    .withUser("Praveen").password(encoder.encode("Praveen@31")).roles("ADMIN")
    .and()
    .withUser("Guru").password(encoder.encode("Praveen@31")).roles("USER");

    }   

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
          .authorizeRequests()
          .antMatchers("/oauth/**","/user","/auth/user").permitAll().anyRequest().authenticated();

    }

}

Код шлюза ZUUL:

SSoВключено .....

   @SpringBootApplication
@EnableZuulProxy
@EnableOAuth2Sso
public class GatewayServiceBooter {

    public static void main(String[] args)
    {
        SpringApplication.run(GatewayServiceBooter.class,args);
    }

}

Свойства GateWay:

   eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

eureka.client.registerWithEureka=true
eureka.client.fetchRegistry=true

eureka.instance.leaseRenewalIntervalInSeconds=3
eureka.instance.leaseExpirationDurationInSeconds=3

eureka.instance.preferIpAddress=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=5000

zuul.sensitiveHeaders=Cookie,Set-Cookie

security.oauth2.client.accessTokenUri=http://localhost:8090/oauth/token
security.oauth2.client.userAuthorizationUri=http://localhost:8090/oauth/authorize
security.oauth2.client.clientId=MyActiveClient
security.oauth2.client.clientSecret=activate
security.oauth2.resource.userInfoUri=http://localhost:8090/user

У меня такое ощущение, что отказ в доступе как-то связан с этой частью, гдеДоступ к API настроен

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
      .authorizeRequests()
      .antMatchers("/oauth/**","/user","/auth/user").permitAll().anyRequest().authenticated();

}

Пожалуйста, помогите мне .... Заранее спасибо

...