pythonflaskoauth-2.0stormpathflask-oauthlib

Flask-Stormpath Token based authentication


I am trying to implement token based authentication for my Flask REST API. I am using Stormpath as my third-party authentication service.

I looked into flask-stormpath built on top of flask-login. Looks like it uses password based authentication as they are trying to maintain session on the server. Also, the documentation doesn't provide me enough information.

Do we have a flask integration for stormpath token based authentication ? If yes, can someone point me to a sample code.

I have already gone through the stormpath/flask-stormpath-sample on github, which again maintains sessions in server.

References:

https://stormpath.com,

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


Solution

  • So here is the way I am currently using until rdegges shall build this feature into flask-stormpath.

    You will need stormpath python sdk latest version and wraps from func tools.

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

    You can create your application as such.

    stormpathClient = Client(id=KEYS['STORMPATH_ID'], secret=KEYS['STORMPATH_SECRET'])
    stormpathApp = stormpathClient.applications.search('your-application')[0]
    

    This decorator shall help you with securing endpoints.

    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)
    

    Let me know in the comments if someone wishes to know the token issuing and refreshing end points as well.