首页 > 解决方案 > 使用 shell 脚本的 JWT 签名问题

问题描述

尝试创建 JWT 文件以请求访问令牌以访问谷歌分析 API。按照本指南 https://developers.google.com/identity/protocols/oauth2/service-account

我创建了一个服务帐户并下载了私钥并编写了一些代码(如下)。我总是收到这样的错误:

"error_description": "错误请求"

我很确定问题出在我签署 JWT 的方式上;确保我也尝试过创建和上传签名(已被 Google 接受)。但什么都没有改变。

echo $(date) - ===================START================================ >> test.log
echo $(date) - writing my JWT >> test.log
echo $(date) - ======================================================== >> test.log

#header
header=$(echo -n '{"alg":"RS256","typ":"JWT"}' | base64) >> test.log
echo $(date) - JWT header: $header >> test.log

#epoch dates calculation
exp=$(date -d "+30 min" +'%s') >> test.log
echo $(date) - expiration time: $exp >> test.log 
iat=$(date +'%s') >> test.log
echo $(date) - issuing time: $iat >> test.log

#------------------
#payload
payload=$(echo -n '{"iss":"*myserviceaccount*","scope":"https://www.googleapis.com/auth/analytics.readonly","aud":"https://oauth2.googleapis.com/token","exp":'$exp',"iat":'$iat'}' | base64 | sed ':a;N;$!ba;s/\n//g') >> test.log
echo $(date) - payload: $payload >> test.log

#------------------
#sign
sign_alg=$header.$payload >> test.log
echo $(date) - sign string: $sign_alg >> test.log

firma=$(echo -n $sign_alg  | openssl dgst -sha256 -sign private_key.pem | base64 | sed ':a;N;$!ba;s/\n//g') >> test.log
echo $(date) - encripted sign: $firma >> test.log

#token request call
#============================
JWT=$header.$payload.$firma >> test.log
echo $(date) - token request: $JWT >> test.log

echo $(date) - token call string >> test.log
curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$JWT' https://oauth2.googleapis.com/token >> test.log

echo $(date) - ====================FINE ELABORAZIONE=================== >> test.log

这里是获取证书和私钥的附加代码:private key

openssl genrsa -out private-key.pem 2048

要上传到谷歌服务帐户的证书

openssl req -new -x509 -key private-key.pem -out cert.pem -days 999

有人可以帮忙吗?

标签: shelloauth-2.0google-apiaccess-tokenservice-accounts

解决方案


为未来的读者编辑我在我的脚本上发现了两个错误,现在它可以工作了

  1. 我需要对我的字符串进行 url 编码| tr '/+' '_-' | tr -d '=')
  2. 顶点:(我最后的电话是

...&断言=$JWT'

代替

...&assertion='$JWT

请注意 ' 的位置


推荐阅读