pass authorization token to headers from Vue.js

356 views
Skip to first unread message

goldli zhang

unread,
Aug 15, 2021, 10:59:59 PM8/15/21
to grpc.io
i built a gRpc Service project by VS2019 C# , and add jwt bearer auth.
i want to pass the token to the rcp service 
follow are the code snaps. 
i don't know how to pass the token , please help.
snap_server.png

and the vue client side 
snap_client_vue.png

goldli zhang

unread,
Aug 15, 2021, 11:18:04 PM8/15/21
to grpc.io
<template>
  <div id="app">
    <img src="./assets/logo.png">
    <i class="el-icon-edit"></i>
    <i class="el-icon-share"></i>
    <i class="el-icon-delete"></i>
    <el-button type="primary" icon="el-icon-search">搜索</el-button>
    <p>
      <el-button type="primary" @click="get1"> 简单rpc [可测试] </el-button>
      <el-button type="primary" @click="get2"> 服务端流rpc [无效] </el-button>
    </p>
    <p>
      <el-button type="primary" @click="loginSys"> login </el-button>
      <el-button type="primary" @click="getToken"> Request token </el-button>
    </p>
    <router-view/>
  </div>
</template>

<script>
// import { HelloRequest, RepeatHelloRequest, HelloReply } from './proto/greet_pb'
import { HelloRequest } from './proto/greet_pb'
import { GreeterClient } from './proto/greet_grpc_web_pb'
import { AppClient } from './proto/app_grpc_web_pb'
import grpc from '#grpc/grpc-js'
// import { Metadata, MetadataValue } from './metadata'
import { CallCredentials } from #grpc/grpc-js/build/src/call-credentials'
// import { Metadata } from '#grpc/grpc-js/build/src/metadata'

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: {
    get1 () {
      var token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiY2xpZW50SWQiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1laWRlbnRpZmllciI6ImNsaWVudElkIiwibmJmIjoxNjI5MDM0MzkxLCJleHAiOjE2MjkwMzQ0NTEsImlzcyI6IkFpMi5XZWIiLCJhdWQiOiJBaTIuV2ViIn0.1QpFsvzRvlBvTPNQ4hzETIDaLfmUsxmVvXaRyXVskjI'
      var metadata = new grpc.Metadata()
      metadata.add('Authorization', 'Bearer ' + token)
      // debugger
      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())
        }
      })
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
Reply all
Reply to author
Forward
0 new messages