【问题标题】:Spring boot : Feign client rest call not working with oauth2, but does work on browserSpring boot:Feign客户端休息调用不适用于oauth2,但可以在浏览器上使用
【发布时间】:2019-05-10 19:26:09
【问题描述】:

有 2 个微服务,一个是 rest 服务,一个是 websocket 服务。 Websocket 服务有 feign 客户端与其余服务对话。

从浏览器工具(例如邮递员)调用 rest 服务时,调用正常。我们只传递带有值Bearer XXXXX 的标头Authorization

在没有拦截器的情况下从 feign 调用时,我们会得到 401:未授权,这是正确的行为。

当将此拦截器添加到代码库时,因为 XXXXX 是真正的令牌,当然,我们会收到 403

@Component
public class FeignOauth2Interceptor implements RequestInterceptor {
    private static final String AUTHORIZATION_HEADER = "Authorization";   
    @Override
    public void apply(RequestTemplate template) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = 
        securityContext.getAuthentication();
        template.header(AUTHORIZATION_HEADER, "Bearer XXXXX");
    }
}

拦截器被调用,因为我们在添加后看到了不同的错误代码,我们从 401 变为 403。

我们在这里缺少什么??

提前致谢

【问题讨论】:

    标签: spring spring-boot oauth-2.0 access-denied feign


    【解决方案1】:

    我认为在拦截器中硬编码令牌不是一个好主意,您可以从 OAuth2AuthenticationDetails 中获取令牌:

    @Bean
    public RequestInterceptor requestTokenBearerInterceptor() {
    
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
                if(authentication == null) return;
                OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
                requestTemplate.header("Authorization", "Bearer " + details.getTokenValue());                   
            }
        };
    }
    

    此外,您还可以使用 OAuth2FeignRequestInterceptor,它从上下文中获取您的令牌并在需要时自行刷新它。在我看来,这是一个更好的解决方案。你可以在这里找到一个使用它的例子:https://stackoverflow.com/a/53454703/10697598

    【讨论】:

    • 感谢您的帮助。代码不是最终的,我确实使用了 OAuth2AuthenticationDetails。问题是一个错误的 url,当找不到端点时,feign 似乎发送了 403。
    猜你喜欢
    • 2011-09-28
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多