Implementing Token Based authentication JWT

844 views
Skip to first unread message

Oasis Agano

unread,
Jun 23, 2017, 4:49:17 PM6/23/17
to web2py-users
Hello,

How can someone implement a token based authentication in web2py;
Both token generation and authorization?


kr,
Oasis

Dave S

unread,
Jun 23, 2017, 5:09:43 PM6/23/17
to web2py-users

gluon/tools.py line 1132 covers the JWT support Niphlod added.
(line 1132 in version 2.14.6, that is)
Nothing in the book yet; the short version of the introduction was in the release notes (one or more of the 2.14's, IIRC).

/dps
 

Oasis Agano

unread,
Jun 24, 2017, 1:03:02 PM6/24/17
to web2py-users
Thank you for your useful answer but how do i pass the username and password
because curl with them returns: Invalid JWT header
when i try to get the login_and_take_token function.

kr,

Oasis

Oasis Agano

unread,
Jun 27, 2017, 5:49:25 AM6/27/17
to web2py-users
the message comes after i add the decorator
on top of a function
@myjwt.allows_jwt()

Oasis Agano

unread,
Jun 27, 2017, 7:17:46 AM6/27/17
to web...@googlegroups.com
Better posting through curl

curl -X POST -d username=oasis...@gmail.com -d password=mypwd
127.0.0.1:8055/masterw2p/default/login_and_take_token

Message has been deleted

Carlos A. Armenta Castro

unread,
Aug 23, 2017, 1:16:19 PM8/23/17
to web2py-users
Very nice!!!

A question: 

in how much time expires the token?

how to know it?




El sábado, 19 de agosto de 2017, 15:31:10 (UTC-7), Oasis Agano escribió:
CONTROLLER


from gluon.tools import AuthJWT
import requests

def index():

response.flash = T("Hello World")
return dict(message=T('Welcome !'))


def user():

return dict(form=auth())


@cache.action()
def download():
"""
allows downloading of uploaded files
http://..../[app]/default/download/[filename]
"""
return response.download(request, db)

def call():
"""
exposes services. for example:
http://..../[app]/default/call/jsonrpc
decorate with @services.jsonrpc the functions to expose
supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
"""
return service()

auth.settings.allow_basic_login = True


@auth.requires_login()
@request.restful()
def api():
response.view = 'generic.'+request.extension
def GET(*args,**vars):
patterns = 'auto'
parser = db.parse_as_rest(patterns,args,vars)
if parser.status == 200:
return dict(content=parser.response)
else:
raise HTTP(parser.status,parser.error)
def POST(table_name,**vars):
return db[table_name].validate_and_insert(**vars)
def PUT(table_name,record_id,**vars):
return db(db[table_name]._id==record_id).update(**vars)
def DELETE(table_name,record_id):
return db(db[table_name]._id==record_id).delete()
return dict(GET=GET, POST=POST, PUT=PUT, DELETE=DELETE)

from gluon.tools import AuthJWT
import requests


myjwt = AuthJWT(auth, secret_key='secretsddfsdfsd')

#this one receives the credentials and gives you a token refer to gluon/tools.py 1132 line
def login_and_take_token():
return myjwt.jwt_token_manager()

@myjwt.allows_jwt()
def protected():
return '%s$%s' % (request.now, auth.user_id)




TERMINAL COMMAND FOR TOKEN GENERATOR

curl -X POST -d username=oasis...@gmail.com -d password=MYPWD 127.0.0.1:8055/masterw2p/default/login_and_take_token

AUTH WITH TOKEN ONLY


curl -H "Authorization: Bearer eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ96lu8kSvANNRtvi23E56I4l_DRq7XA" http://127.0.0.1:8055/ntwaza/default/protected


MODEL CONFIG

from gluon.tools import Auth, Service, PluginManager,AuthJWT,AuthAPI

# host names must be a list of allowed host names (glob syntax allowed)
auth = Auth(db, host_names=myconf.get('host.names'))
service = Service()
plugins = PluginManager()
auth.settings.allow_basic_login = True
myjwt = AuthJWT(auth, secret_key='secretsddfsdfsd')







On Friday, June 23, 2017 at 10:49:17 PM UTC+2, Oasis Agano wrote:

Carlos A. Armenta Castro

unread,
Aug 23, 2017, 2:09:15 PM8/23/17
to web2py-users
My 1 cent.

How to use AuthJWT with requests python library (client):

import requests
credentials = {'username': 'chum...@xxx.com', 'password': 'mypasswordhere'}
if r.status_code == 200: 
    #Get Token and contruct the header
    token = r.json()['token']
    headers = {'Authorization': 'Bearer ' + token}
    protected_data = requests.get("http://127.0.0.1:8000/myapp/default/protected", headers=headers)
    print(protected_data.text)
else:
    print('ERROR when logging')


Oasis Agano

unread,
Aug 30, 2017, 8:01:25 AM8/30/17
to web2py-users
Hi carlos,
I havent played with token expiration that much but i think it is possible to set it,  check the
gluon/tools.py 1132 line doc
Reply all
Reply to author
Forward
0 new messages