所以这是我目前使用的方式,直到rdegges将此功能构建到flask-stormpath
.
您将需要 Stormpath python sdk 最新版本并从 func 工具包装。
from stormpath.api_auth import (PasswordGrantAuthenticator, RefreshGrantAuthenticator, JwtAuthenticator)
from functools import wraps
您可以这样创建您的应用程序。
stormpathClient = Client(id=KEYS['STORMPATH_ID'], secret=KEYS['STORMPATH_SECRET'])
stormpathApp = stormpathClient.applications.search('your-application')[0]
该装饰器将帮助您保护端点。
def tokenRequired(func):
"""
Decorator to apply on all routes which require tokens.
"""
@wraps(func)
def wrappingFunc():
#check the auth header of the request for a bearer token.
authHeader = request.headers.get('Authentication')
#make sure that the string is a bearer type.
if len(authHeader)<8 or (not authHeader[:7] == 'Bearer ') or (
not authHeader):
return Response("401 Unauthorized",401)
authToken = authHeader[7:]
try:
authenticator = JwtAuthenticator(stormpathApp)
authResult = authenticator.authenticate(authToken)
request.vUser = authResult.account
except:
return Response("403 Forbidden",403)
return func()
return wrappingFunc
#Use this decorator like below.
@flaskApp.route('/secure-route',methods=['GET','POST'])
@tokenRequired
def secureEndpoint():
# return JSON based response
return Response("This is secure Mr." + request.vUser.given_name ,200)
如果有人想知道令牌发行和刷新端点,请在评论中告诉我。