Access an authenticated grpc service using grpc-web
Use interceptors to add the Authorization
header for each request. (Or any other header for that matter)
For this to work you need grpc-web version >= 1.1.0
. Latest version is 1.2.1
class AuthInterceptor {
token: string
constructor(token: string) {
this.token = token
}
intercept(request: any, invoker: any) {
const metadata = request.getMetadata()
metadata.Authorization = 'Bearer ' + this.token
return invoker(request)
}
}
const authInterceptor = new AuthInterceptor(token)
options = {
unaryInterceptors: [authInterceptor],
streamInterceptors: [authInterceptor]
}
const service = new GrpcServicePromiseClient(
host,
null,
options
)
Now every call to the grpc service will have the Authorization
header with the provided token.