如何从 Vue.js 向 gRpc 标头添加授权

Posted

技术标签:

【中文标题】如何从 Vue.js 向 gRpc 标头添加授权【英文标题】:how to add authorization to gRpc headers from Vue.js 【发布时间】:2021-10-17 22:23:16 【问题描述】:

首先。我从 VS2019 创建了一个 gRpc 服务项目,并添加了 Jwt Bearer Authentication and Authorization。 当客户端应用程序(VS code + Vue.js)请求登录服务方法时,将发送一个令牌。

string key = "AB6B4DC1-FABF-47AE-A585-4AD154758B05";
var securityKey = new SymmetricSecurityKey(Guid.Parse(key).ToByteArray());
var claims = new[] 
    new Claim(ClaimTypes.Name, clientId),
    new Claim(ClaimTypes.NameIdentifier,clientId)
;

var token = new JwtSecurityToken("client",
    "client",
    claims,
    notBefore:DateTime.Now,
    expires: DateTime.Now.AddSeconds(60),
    signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
    );

return new JwtSecurityTokenHandler().WriteToken(token);

然后是jwt配置

var key = "AB6B4DC1-FABF-47AE-A585-4AD154758B05";

options.TokenValidationParameters = new TokenValidationParameters

    ClockSkew = TimeSpan.FromSeconds(30),
    ValidateIssuer = true,
    ValidateAudience = true,
    AudienceValidator = (m, n, z) =>
    
        return m != null && m.FirstOrDefault().Equals("");
    ,
    ValidateLifetime = true,
    ValidateIssuerSigningKey = true,
    ValidAudience = "client",
    ValidIssuer = "client",
    IssuerSigningKey = new SymmetricSecurityKey(Guid.Parse(key).ToByteArray())
;

问题是我无法将授权作为标题项传递给 gRpc 服务器 代码如下:

'

import  Metadata  from '@grpc/grpc-js/build/src/metadata'
import  CallCredentials  from '@grpc/grpc-js/build/src/call-credentials'

export default 
  name: 'App',
  created () 
    this.client = new GreeterClient('https://localhost:5001', CallCredentials.createFromPlugin, null)
    this.appClient = new AppClient('https://localhost:5001', null, null)
  ,
  methods: 
    loginSys () 
      var lm = new LoginModel()
      lm.setLoginname('admin')
      lm.setLoginpwd('abc123!@#')
      lm.setLogincode('kkkkkrrr')

      var appInfo = new AppInfo()
      appInfo.setAppid('asdfasdfasdf')
      appInfo.setApptoken('12345678901234567890')
      appInfo.setModel(lm)

      this.appClient.login(appInfo, , (err, response) => 
        debugger
        if (err) 
          console.log(`Unexpected error for sayHello: code = $err.code, message = "$err.message"`)
         else 
          console.log(response.getMessage())
          console.log(response.getIssucceed())
          if (response.hasUserinfo()) 
            var userInfo = response.getUserinfo()
            console.log(userInfo.getAvatar())
            console.log(userInfo.getUsername())
            console.log(userInfo.getCellphone())
          
        
      )
    ,
    get1 () 
      var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiY2xpZW50SWQiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6ImNsaWVudElkIiwibmJmIjoxNjI5MDM0MzkxLCJleHAiOjE2MjkwMzQ0NTEsImlzcyI6IkFpMi5XZWIiLCJhdWQiOiJBaTIuV2ViIn0.1QpFsvzRvlBvTPNQ4hzETIDaLfmUsxmVvXaRyXVskjI'

      var metadata = new Metadata()
      metadata.add('authorization', 'Bearer ' + token)

      var request = new HelloRequest()
      request.setName('World')
      this.client.sayHello(request, metadata, (err, response) => 
        if (err) 
          console.log(`Unexpected error for sayHello: code = $err.code, message = "$err.message"`)
         else 
          console.log(response.getMessage())
        
      )
    
  

方法:get1 用于做“授权”测试。 当我执行此方法时,我发现 http 标头中不存在授权。 我不知道为什么,我该怎么办?

【问题讨论】:

【参考方案1】:

我得到了答案。

  const token = 'eyJhbGciOiJIUzyXVskjI'
  const metadata =  'authorization': 'Bearer ' + token 

【讨论】:

以上是关于如何从 Vue.js 向 gRpc 标头添加授权的主要内容,如果未能解决你的问题,请参考以下文章

骆驼如何将授权标头添加到休息路线?

向标头添加授权

如何在 POSTMAN 环境中添加授权标头?

如何使用js或jQuery向ajax请求添加自定义HTTP标头?

向标头添加授权

如何从 Vue.Js 中的变量向数组添加值以制作条形图