Firebase DB HTTP API Auth:何时以及如何刷新JWT令牌? [英] Firebase DB HTTP API Auth: When and how to refresh JWT token?
问题描述
我尝试使用HTTP API将Python webapp写入Firebase数据库(我正在使用在Google I / O 2016上展示的Firebase新版本)。
到目前为止,我的理解是,我想要完成的特定类型的写入是通过对这种类型的URL进行POST请求来完成的:
https://my-project-id.firebaseio.com/ {path-to-resource} .json
什么我缺少的是身份验证部分:如果我得到它正确的JWT应该作为授权:持证人{令牌}
。 b
$ b因此,我创建了一个服务帐户,下载了它的私钥并用它来生成JWT,并将其添加到请求标头,并将请求成功写入到Firebase DB中。
现在JWT已经过期,任何类似的对firebase DB的请求都失败了。
当然,我应该生成一个新的令牌,问题是:我不期望处理令牌生成和refr esh自己,大部分的HTTP API我只需要在请求中传递一个静态api键,所以我的web应用程序可以保持相对简单,只需要添加stati api键字符串到请求中即可。
如果我必须考虑令牌生成和过期,webapp逻辑需要变得更加复杂(因为我必须存储令牌,检查它是否仍然有效,并在产生新消息时生成新令牌不),或者我可以为每个请求生成一个新的标记(但是这真的有道理吗?)。
我想知道是否有最佳做法在这方面或如果我从这个主题的文件丢失的东西。
谢谢,
马可
ADDENDUM
这是我正在运行的代码:
导入请求
从oauth2client.service_account导入json
导入ServiceAccountCredentials
_BASE_URL ='https:// my-app-id.fi rebaseio.com'
_SCOPES = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/ firebase.database'
]
$ b $ def _get_credentials():
credentials = ServiceAccountCredentials.from_json_keyfile_name('my_service_account_key.json',scopes = _SCOPES)
returns credentials.get_access_token ().access_token
$ b $ def post_object():
url = _BASE_URL +'/path/to/write/to.json'
headers = {
'Authorization':'Bearer'+ _get_credentials(),
'Content-Type':'application / json'
}
payload = {
' title':title,
'message':alert
}
return requests.post(url,
data = json.dumps(payload),$ b $目前为每个请求生成一个新的JWT。这对我来说似乎并不理想。是否有可能生成一个不会过期的令牌?解决方案感谢代码示例。通过使用credentials.authorize函数为http创建一个经过身份验证的包装器,可以更好地工作。
from oauth2client.service_account import ServiceAccountCredentials从httplib2导入
Http
导入json
_BASE_URL ='https://my-app-id.firebaseio.com'
_SCOPES = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/firebase.database'
]
#获取凭证以进行对firebase的授权调用
credentials = ServiceAccountCredentials.from_json_keyfile_name(
_KEY_FILE_PATH,scopes = _SCOPES)
#在凭证中包装http。所有后续的调用都被认证
http_auth = credentials.authorize(Http())
$ b $ def post_object(path,objectToSave):
url = _BASE_URL + path
resp,content = http_auth.request(
uri = url,
method ='POST',
headers = {'Content-Type':'application / json'},
body = json.dumps(objectToSave),
)
返回内容
objectToPost = {
'title':title,
'message':alert
}
print post_object('/ path / to / write / to.json',objectToPost)
I'm trying to make a Python webapp write to Firebase DB using HTTP API (I'm using the new version of Firebase presented at Google I/O 2016).
My understanding so far is that the specific type of write I'd like to accomplish is made with a POST request to a URL of this type:
https://my-project-id.firebaseio.com/{path-to-resource}.json
What I'm missing is the auth part: if I got it correctly a JWT should be passed in the HTTP Authorization header as Authorization : Bearer {token}
.
So I created a service account, downloaded its private key and used it to generate the JWT, added it to the request headers and the request successfully wrote to Firebase DB.
Now the JWT has expired and any similar request to the firebase DB are failing.
Of course I should generate a new token but the question is: I wasn't expecting to handle token generation and refresh myself, most HTTP APIs I'm used to require just a static api key to be passed in the request so my webapps could be kept relatively simple by just adding the stati api key string to the request.
If I have to take care of token generation and expiration the webapp logic needs to become more complex (because I'd have to store the token, check if it is still valid and generate a new one when not), or I could just generate a new token for every request (but does this really make sense?).
I'd like to know if there's a best practice to follow in this respect or if I'm missing something from the documentation regarding this topic.
Thanks,
Marco
ADDENDUM
This is the code I'm currently running:
import requests
import json
from oauth2client.service_account import ServiceAccountCredentials
_BASE_URL = 'https://my-app-id.firebaseio.com'
_SCOPES = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/firebase.database'
]
def _get_credentials():
credentials = ServiceAccountCredentials.from_json_keyfile_name('my_service_account_key.json', scopes=_SCOPES)
return credentials.get_access_token().access_token
def post_object():
url = _BASE_URL + '/path/to/write/to.json'
headers = {
'Authorization': 'Bearer '+ _get_credentials(),
'Content-Type': 'application/json'
}
payload = {
'title': title,
'message': alert
}
return requests.post(url,
data=json.dumps(payload),
headers=headers)
Currently for every request a new JWT is generated. It doesn't seem optimal to me. Is it possible to generate a token that doesn't expire?
解决方案 Thanks for the code example. I got it working better by using the credentials.authorize function which creates an authenticated wrapper for http.
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
import json
_BASE_URL = 'https://my-app-id.firebaseio.com'
_SCOPES = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/firebase.database'
]
# Get the credentials to make an authorized call to firebase
credentials = ServiceAccountCredentials.from_json_keyfile_name(
_KEY_FILE_PATH, scopes=_SCOPES)
# Wrap the http in the credentials. All subsequent calls are authenticated
http_auth = credentials.authorize(Http())
def post_object(path, objectToSave):
url = _BASE_URL + path
resp, content = http_auth.request(
uri=url,
method='POST',
headers={'Content-Type': 'application/json'},
body=json.dumps(objectToSave),
)
return content
objectToPost = {
'title': "title",
'message': "alert"
}
print post_object('/path/to/write/to.json', objectToPost)
这篇关于Firebase DB HTTP API Auth:何时以及如何刷新JWT令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!