2016-07-08 4 views
0

У меня есть приложение, пытающееся вызвать RESTApi под прокси-сервером Zuul.zuul: аутентификация на предъявителя не принимается

Приложение имеет действительный токен jwt, заданный сервером OAuth2. У меня был маркер в разрешении на предъявителя в заголовке, но у меня есть (ответ «Полная аутентификация требуется для доступа к этому ресурсу») от сервера zuul.

Моя Zuul конфигурация:

eureka: 
    client: 
     registerWithEureka: true 
     fetchRegistry: true 
     serviceUrl: 
      defaultZone: http://localhost:8761/eureka/ 
    instance: 
     leaseRenewalIntervalInSeconds: 10 
     statusPageUrlPath: ${management.context_path}/info 
     healthCheckUrlPath: ${management.context_path}/health 

server: 
    port: 80 
management: 
    port: 81 
    context_path: /admin 

security: 
    sessions: stateless 
     # Disable Spring Boot basic authentication 
    basic: 
     enabled: false 

endpoints: 
    restart: 
     enabled: true 
    shutdown: 
     enabled: true 
    health: 
     sensitive: false 

# The OAuth2 server definition that would be used to send the authorization requests to 
authserver: 
    hostname: localhost 
    port: 9000 
    contextPath: uaa 

spring: 
    oauth2: 
     resource: 
      userInfoUri: http://${authserver.hostname}:${authserver.port}/${authserver.contextPath}/user 
      jwt.key-uri: http://${authserver.hostname}:${authserver.port}/${authserver.contextPath}/oauth/token_key 
      preferTokenInfo: false 

    output: 
     ansi: 
      enabled: ALWAYS 

Основной Zuul файл:

@SpringBootApplication 
@EnableZuulProxy 
@EnableResourceServer 
public class ZuulApplication { 

    public static void main(String[] args) { 
     new SpringApplicationBuilder(ZuulApplication.class).web(true).run(args); 
    } 
} 

Zuul конфигурация безопасности файла:

@Configuration 
public class WebSecurityConfiguration extends ResourceServerConfigurerAdapter { 

    @Override 
    public void configure(HttpSecurity http) throws Exception { 
     http 
       .csrf().disable() 
       .exceptionHandling() 
       .and() 
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
       .and() 
       .authorizeRequests() 
        .antMatchers("/admin/trace").permitAll() 
        .anyRequest().authenticated() 
       ; 
    } 

} 

Зов restApi:

 final String access_token = (String) httpSession.getAttribute(OAuthComponent.HTTPSESSION_OAUTH_ACCESS_TOKEN); 

     final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); 
     headers.add("Authorization", "Bearer " + access_token); 
     headers.add("Content-Type", "application/json"); 

     final HttpEntity<Object> request = new HttpEntity<>(searchParams,headers); 

     return restOperations.postForObject("http://localhost/ms-arbre-recherche/utilisateur/search", request, Object.class); 

Я использую весеннее облако Brixton SR2 и весеннюю обувь 1.4.0RC1.

+0

У вас есть пример на мерзавца, чтобы иметь Посмотрите на это? – carlitos081

+0

Извините, нет примера git. – BokC

ответ

1

Это моя конфигурация безопасности:

@Configuration 
@EnableResourceServer 
public class JwtSecurityConfig extends ResourceServerConfigurerAdapter{ 

    @Override 
    public void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests() 
      .antMatchers("/oauth/**").permitAll() 
      .antMatchers("/**").hasAuthority("ROLE_API") 
      .and() 
      .csrf().disable(); 
    } 
} 

Главного, что я делаю отличаюсь тем, что я использую OauthRestTemplate.

@Configuration 
public class ActivationApiEndpointConfig { 

    @Bean 
    protected OAuth2ProtectedResourceDetails resource() { 

     ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails(); 



    resource 

.setAccessTokenUri("http://cdpsit04is01.eng.rr.com:8888/oauth/token"); 

     resource.setClientId("clientid"); 
     resource.setClientSecret("clientsecret"); 
     resource.setGrantType("client_credentials"); 
     resource.setScope(Arrays.asList("write", "read")); 
     resource.setAuthenticationScheme(AuthenticationScheme.header); 

     return resource; 
    } 

    @Bean 
    public OAuth2RestOperations applicationApiTemplate() { 
     AccessTokenRequest atr = new DefaultAccessTokenRequest(); 

     return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr)); 
    } 

} 

А потом

String returnValue = applicationApiTemplate.getForObject(uri.expand(pathVariables).toUri(), String.class); 

Вы также должны убедиться, что у вас есть это в вашем ПОМ (или зависит):

<dependency> 
    <groupId>org.springframework.security.oauth</groupId> 
    <artifactId>spring-security-oauth2</artifactId> 
</dependency> 
<dependency> 
    <groupId>org.springframework.security</groupId> 
    <artifactId>spring-security-jwt</artifactId> 
</dependency> 
Смежные вопросы