我正在尝试为我的 Flask REST API 实现基于 token 的身份验证。我正在使用 Stormpath 作为我的第三方身份验证服务。
我查看了构建在 flask-login
之上的 flask-stormpath
。看起来它使用基于密码的身份验证,因为他们试图在服务器上维护 session 。此外,文档没有为我提供足够的信息。
我们是否有用于基于 stormpath token 的身份验证的 flask 集成? 如果是,有人可以指出示例代码吗?
我已经在 github 上查看了 stormpath/flask-stormpath-sample
,它再次在服务器中维护 session 。
引用资料:
最佳答案
所以这就是我目前使用的方式,直到 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)
如果有人想知道 token 发行和刷新端点,请在评论中告诉我。
关于python - 基于 Flask-Stormpath token 的身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37179915/