shell - 使用 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
有人可以帮忙吗?
解决方案
为未来的读者编辑我在我的脚本上发现了两个错误,现在它可以工作了
- 我需要对我的字符串进行 url 编码
| tr '/+' '_-' | tr -d '=')
- 顶点:(我最后的电话是
...&断言=$JWT'
代替
...&assertion='$JWT
请注意 ' 的位置
推荐阅读
- r - 在一列中保留来自 emmeans::contrast 的 p 值格式,在其他列中保留合理数量的小数点
- sequelize.js - 续集两个事实来源(迁移和模型)
- python - 合并具有相同列的多个数据框并删除 nans
- javascript - Https请求node.js
- emacs - 如何为所有 Emacs 备份文件设置最大总大小?
- reactjs - 反应部署和搜索引擎问题
- java - 学习 Java 类和方法,在测试我的代码时遇到此错误
- python - pandas 中基于 2 列条件的条件运行计数(根据时间戳计算队列中的人数)
- odoo - Odoo KeyError:“set_scrollTop”和“ir.actions.do_nothing”
- python - 如何通过使用其他列表的值将索引插入第一个列表,将一个列表的值插入另一个列表?(Python)