spring cloud feign Security远程调用401

4,214 阅读1分钟

问题描述

引用Spring Cloud Security之后通过Feign远程调用其他服务接口时会报401错误

public UserDetails loadUserByUsername(String username) {
        ServerResponse<UserInfo> result = userSysUserFeignApi.info(username);
        UserDetails userDetails = getUserDetails(result);
        return userDetails;
}

调用 userSysUserFeignApi.info(username); 会出现以下错误

{"timestamp":1524018915085,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/angelcloud-provider-user/user/info"}

解决办法

  1. 添加yml配置文件
security:
  oauth2:
    client:
      clientId: yourClientId
      clientSecret: yourClientSecret
      accessTokenUri: http://localhost:3000/oauth/token
      grant-type: client_credentials
      scope: service
    resource:
      user-info-uri: http://localhost:3000/me
  1. 编写Feign拦截器
@Configuration
public class FeignConfig {
    @Bean
    @ConfigurationProperties(prefix = "security.oauth2.client")
    public ClientCredentialsResourceDetails clientCredentialsResourceDetails() {
        return new ClientCredentialsResourceDetails();
    }

    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor(){
        return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), clientCredentialsResourceDetails());
    }

    @Bean
    public OAuth2RestTemplate clientCredentialsRestTemplate() {
        return new OAuth2RestTemplate(clientCredentialsResourceDetails());
    }
}