Add Simple Authentication On Your Flask-Restful App

pomain buthi
3 min readJun 25, 2020

# this article will be a part of “what I learn as a freshman”

Target

After a long time hard work, I finally managed to build a shit hole with flask-restful. Now the app need to have some authentication, we already have a outline login verify system, which accept username/password and return a ticket for further usage.

Tools

auth part

For flask back-end, flask_httpauth will be a good library for help. We just need to do four step to add authentication with it.

  1. Install and update using pip:
pip install -U Flask-HTTPAuth
  1. Import one authentication class and create an global object of it
from flask_httpauth import HTTPBasicAuth
auth = HTTPBasicAuth()
##########################you can also use digest auth##############
from flask_httpauth import HTTPDigestAuth
auth = HTTPDigestAuth()
#########################token auth is what we will use#############
from flask_httpauth import HTTPTokenAuth
auth = HTTPTokenAuth(scheme='Bearer')
#for detail params of these class, pls check their docs

3. Set an auth method (token example)

@auth.verifytoken
def verifytokenmethodwithanyname(token):
#here use your own method verify token
if token is 'right_token':
return True
else:
return False

4. Tell the auth which api you need it to do the auth

@app.route('/')
@auth.login_required # just add this line for auth
def index():
return "Hello"
######flask-restful use different code structure as below#######
class MainPage(Resource):
@auth.login_required #just add here
def get():
return 'Hello'
api.add_resource(MainPage,'/main')

also in my simple usage, i want the server return 403(default 401) when didn’t receive token, flask_httpauth also provide method

@auth.error_handler
def auth_error():
return "Access Denied", 403 #this is flask-restful return 403

token generation

I use itsdangerous library to create token. Very simple.

  1. Install and update using pip:
pip install -U itsdangerous

2. Import it

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer # you can also use URLSafeSerializer, more safe

3. encode some information into token

s = Serializer("seceretkey", expires_in = 600)#create a temp object
token = s.dumps(information)#here token is not jsonable string
token.decode('ascii')# use this to convert it to simple string

4. decode some information

from itsdangerous.exc import BadSignature,SignatureExpireds = Serializer(config['SECRET_KEY'])
try:
information = s.loads(token)
except SignatureExpired:
print('token expired')
return None
except BadSignature:
print('wrong token')
return None

Now we can achieve a simple Authentication for this flask-restful project.

In fact, for original flask project, we should

from flask import g

then a token-session connection was build.

But flask-restful suggest not using token-session structure, still trying to figure out why, so for now didn’t add it.

What I Learn

If the target was not clear enough at the beginning, then build a project will some framework that’s not very well-known might cause very dangerous situation. In this example, I have to admit after a few time of changing requirement, my code has been some shit hole, even every line was written by me.

Flask-restful is very suitable for building some light app, it’s fast and has more clear structure, but as the price it lock some methods inside, so the extension is not good enough.

Searching with google when meet any problem do help, but I still need a notebook. So here it is, a part of “what I learn as a freshman”.

--

--