【问题标题】:Flask-Stormpath Token based authentication基于 Flask-Stormpath 令牌的身份验证
【发布时间】:2016-05-12 07:20:44
【问题描述】:

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

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

我们有用于基于 Stormpath 令牌的身份验证的烧瓶集成吗? 如果是,有人可以指出我的示例代码。

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

参考资料:

https://stormpath.com,

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

【问题讨论】:

    标签: python flask oauth-2.0 stormpath flask-oauthlib


    【解决方案1】:

    这是我目前使用的方式,直到 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)
    

    如果有人想知道令牌发行和刷新端点,请在 cmets 中告诉我。

    【讨论】:

      【解决方案2】:

      我是 Flask-Stormpath 库的作者。答案是不。我实际上正在开发一个新版本的库(大约一个月后发布),它将默认提供此功能,但目前它仅支持基于会话的身份验证。

      【讨论】:

      • 现在提供支持吗? (4 年后)
      • @rdegges,你能看看我目前使用的临时方式(在下面的答案中)并制作 cmets。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2016-01-23
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      相关资源
      最近更新 更多