首页 文章

Spring Cloud Zuul通过JWT下游

提问于
浏览
2

我已经阅读了很多围绕这个的问题,但似乎没有一个类似于我已经拥有JWT的边缘情况 .

我在我的前端使用Auth0(注意auth-zero,而不是Oauth)来获得一个JWT,它为我的后端加载了范围和身份验证 . 当我登录到我的前端客户端时,我得到了一个带有access_token的JWT . 如果我复制该令牌,我可以向我的后端微服务发出直接卷曲请求

curl -X GET -H "Authorization: Bearer TOKEN_HERE" -H "Cache-Control: no-cache" "http://192.168.0.109:39885"

这按预期工作,我收到200响应 . 尼斯 .

现在,当我通过我的Zuul代理尝试相同的卷曲请求时,我得到一个令人讨厌的401 .

我的网关配置是:

@EnableHystrix
@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class EdgeServiceApplication {

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

现在阅读来自辉煌的Syer博士的documentationthis对话,我知道我需要允许 Headers 进入我已经完成的下游:

zuul:
  sensitiveHeaders:
  routes:
    instances:
      path: /instances/**
      serviceId: instance-service
    restore:
      path: /restore/**
      serviceId: restore-service

sensitiveHeaders 设置为空应该允许所有内容(当然用于测试) .

进一步查看文档,我看到我需要将 @EnableOAuth2Sso 添加到我的Zuul配置中 . 这是我感到困惑/事情破裂的地方 .

据我所知, @EnableOAuth2Sso 用于生成和验证令牌 . 我不想那样做 . 我已经为我的微服务准备好了很好的令牌(在那里验证了它) .

我如何告诉Zuul不要弄乱我的JWT并且只是发送它们?

1 回答

  • 2

    我已经解决了这个问题,我的代码中有许多问题需要详细说明,但问题的要点是:

    • 当我刚刚发送 access_token 时,我试图将整个JWT发送到微服务器

    • 当我尝试发送 access_token 时,ember-simple-auth0实际上默认发送 id_token

    • 我需要配置Zuul将CORS请求直接传递给微服务

    一旦我开始发送 access_token 而不是 id_token ,很容易开始调试问题 .

    要告诉ember-simple-auth0使用 access_token ,而是使用以下内容添加新的授权程序:

    // app/authorizers/application.js    
    import Ember from 'ember';
        import BaseAuthorizer from 'ember-simple-auth/authorizers/base';
        const {
          isPresent,
          debug
        } = Ember;
    
        export default BaseAuthorizer.extend({
          authorize(sessionData, block) {
            let userToken = sessionData['accessToken'];
    
            if (isPresent(userToken)) {
              block('Authorization', `Bearer ${userToken}`);
            } else {
              debug('Could not find the authorization token in the session data for the jwt authorizer.');
            }
          }
        });
    

    然后记得告诉你的适配器使用新的授权器:

    export default DS.JSONAPIAdapter.extend(DataAdapterMixin, {
      authorizer: 'authorizer:application',
    });
    

    要将CORS转发到您的微服务,请使用:

    spring:
      mvc:
        dispatch-options-request: true
    

    并确保您没有从请求中删除 Headers :

    zuul:
      sensitiveHeaders:
      routes:
        instances:
          path: /instances/**
          serviceId: instance-service
          stripPrefix: false
    
        restore:
          path: /restore/**
          serviceId: restore-service
          stripPrefix: false
    

    希望有人发现这很有用 .

相关问题