基于FlaskStormpath令牌的身份验证

2024-09-30 20:25:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我的flaskrestapi实现基于令牌的身份验证。我正在使用Stormpath作为我的第三方身份验证服务。在

我研究了建立在flask-login之上的flask-stormpath。看起来它使用了基于密码的身份验证,因为他们试图在服务器上维护会话。另外,文件也没有给我提供足够的信息。在

我们是否为基于stormpath令牌的身份验证提供了烧瓶集成? 如果是,有人能给我指一个示例代码吗。在

我已经看过github上的stormpath/flask-stormpath-sample,它再次在服务器中维护会话。在

参考文献:

https://stormpath.com

https://github.com/stormpath/stormpath-flask


Tags: 文件httpsgithub服务器com身份验证信息密码
2条回答

所以我现在使用的方法是,直到rdegges将这个特性构建到flask-stormpath中。在

您需要stormpath python sdk的最新版本和func tools的包装。在

from stormpath.api_auth import (PasswordGrantAuthenticator, RefreshGrantAuthenticator, JwtAuthenticator)
from functools import wraps

您可以这样创建应用程序。在

^{pr2}$

这个装饰器将帮助您保护端点。在

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)

如果有人想知道代币发行和刷新的终点,请在评论中告诉我。在

我是Flask Stormpath图书馆的作者。答案是否定的。我实际上正在开发一个新版本的库(大约一个月后发布),默认情况下它将提供此功能,但现在它只支持基于会话的身份验证。在

相关问题 更多 >