Spring Security Аутентификация и сервер ресурсов разделены check_token не отправляет заголовок авторизации (outh2 jwt spring boot, zuul) - PullRequest
0 голосов
/ 26 апреля 2019

проблема

сервер ресурсов делает запрос для check_token о своем непроходном токене авторизации, который реализуется Spring Security. как мы можем передать токен авторизации для конечной точки / check_token?

Я использую zuul в качестве шлюза API, и все запросы проходят только через zuul. я создал сервер аутентификации, который является сервером аутентификации (весенний облачный проект) и код приведен ниже для авторизации, и я регистрирую аутентификациюManager с webSecurityConfigurationAdapter код указан ниже

AuthorizationServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


    @Autowired
    @Qualifier("userDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Value("${config.oauth2.tokenTimeout}")
    private int expiration;

    @Value("${config.oauth2.privateKey}")
    private String privateKey;

    @Value("${config.oauth2.publicKey}")
    private String publicKey;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("client")
                .secret(passwordEncoder().encode("secret"))
                .authorizedGrantTypes("client_credentials", "password", "refresh_token", "authorization_code")
                .scopes("read", "write", "trust")
                .accessTokenValiditySeconds(expiration)
                .refreshTokenValiditySeconds(expiration);

    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {


        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(privateKey);

        return converter;
    }

    @Bean
    public JwtTokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Value("${filters.cors.allowed.origin}")
    private String allowedOriginUrlForCordFilter;

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true); 
        config.addAllowedOrigin(allowedOriginUrlForCordFilter);
        //config.addAllowedOrigin("http://localhost:8080/");
        config.addAllowedHeader("*");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }


    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setClientDetailsService(clientDetailsService);
        defaultTokenServices.setSupportRefreshToken(true);
        defaultTokenServices.setTokenEnhancer(accessTokenConverter());
        return defaultTokenServices;
    }

    /**
     * Defines the authorization and token endpoints and the token services
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .tokenStore(tokenStore())
                .tokenServices(tokenServices())
                .accessTokenConverter(accessTokenConverter());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security.checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }
}

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

ResourceServerConfiguration.java

@Configuration
@EnableResourceServer
@EnableWebSecurity(debug = true)
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    // private static final Logger LOGGER =
    // Logger.getLogger(ResourceServerConfiguration.class);

    @Value("${config.oauth2.publicKey}")
    private String publicKey;

    @Value("${config.oauth2.privateKey}")
    private String privateKey;

    @Value("${config.oauth2.resource.id}")
    private String resourceId;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().anonymous().disable().authorizeRequests()
                // .antMatchers(HttpMethod.OPTIONS).permitAll()
                // .antMatchers("/oauth/**").authenticated()
                .antMatchers("/register/**").authenticated();
    }

    // @Override
    // public void configure(ResourceServerSecurityConfigurer resources) {
    // resources.resourceId(resourceId).tokenServices(tokenServices()).tokenStore(tokenStore());
    // }

    // @Bean
    // @Primary
    // public DefaultTokenServices tokenServices() {
    // DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
    // defaultTokenServices.setTokenStore(tokenStore());
    // defaultTokenServices.setSupportRefreshToken(true);
    // defaultTokenServices.setTokenEnhancer(accessTokenConverter());
    // return defaultTokenServices;
    // }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {

        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(privateKey);

        return converter;
    }

    @Bean
    public JwtTokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Primary
    @Bean
    public RemoteTokenServices tokenServices() {
        final RemoteTokenServices tokenService = new RemoteTokenServices();
    tokenService.setCheckTokenEndpointUrl("http://localhost:8765/auth/oauth/check_token/");
        tokenService.setClientId("client");
        tokenService.setClientSecret("secret");
        //tokenService.setTokenName("");
        // tokenService.setTokenStore(tokenStore());
        // tokenService.setSupportRefreshToken(true);
        tokenService.setAccessTokenConverter(accessTokenConverter());
        return tokenService;
    }
}

теперь возникает проблема, когда сервер ресурсов делает запрос для check_token, там я не могу передать авторизационный токен.

...