‘‘‘
The JWT represents the JSON Web token, which is a token format for authenticating the head. This token helps you to deliver information in a secure way between the two systems.
We'll take the JWT as "bearer token" for the moment. A bearer token consists of three parts: Header,payload,signature.
The header is part of the token and is used to store the token type and encoding, usually using BASE-64 encoding.
The payload contains information. You can store any kind of information, such as user information, product information, etc. They are all stored using the Base-64 encoding method.
The signature includes a mixture of header,payload and keys. The key must be securely bunkers stored on the server side.
(https://zhuanlan.zhihu.com/p/19920223)
‘‘‘
Https://github.com/jpadilla/pyjwt
#-*-coding:utf-8-*-import Jwtsecret = B '??? \\\//>000 ' encoded = Jwt.encode ({' User ': ' Bottle '}, Secret, algorithm= ' HS256 ') print encodeddecoded = Jwt.decode ( Encoded, secret, algorithms=[' HS256 ']) print decoded
Save user data with MongoDB
Use bottle to do the service
- config.py
Class settings (object): host = ' localhost ' port = 12306 secret = B '---------00000??? \\‘
- MongoDB Save Data
User ={ ' name ': ' User1 ', ' passwd ': ' passwd ', ' ident ': 0 #public}admin = { ' name ': ' Bottle ', ' passwd ': ' passwd2 ', ' ident ': 1 #admin}
- /login Routing
@app. Route ('/login ', method= ' POST ') def login (): name = request.forms.get (' name ') passwd = Request.forms.get (' passwd ') ret = db.user.find_one ({' name ': name}) if ret and ret[' passwd '] = = passwd: if Ret.get (' token ', None): res = { ' status ': False, ' data ': ' Error occured: ' + ' User already logined! ' } return res token = jwt.encode ({' User ': Name, ' ident ': ret[' ident ']}, Settings.secret, algorithm= ' HS256 ') db.user.update ({' name ': name}, {' $set ': {' token ': token}}) res = { ' status ': True, ' data ': Name, ' token ': Token } return res Else: res = { ' type ': False, ' data ': ' Error occured: ' + ' User name ' or password wrong!!! ' } return res
- login_required Verification
def login_required (): Def decorator (func): Def wrapper ( *args, **kwargs): Authorization = request.headers. get ( " ' ' if
returnreturn decorator
- /me Test Routing
@app. Route ('/me ') @login_required () def Me (token): ret = db.user.find_one ({' token ': token}) if ret: Ret.pop (' _id ') res = { ' type ': True, ' data ': Ret } return res else: res = { ' Type ': False, ' data ': ' Error occured: ' + ret } return res
Using Curl Testing
Get tokencurl-d ' name=bottle&passwd=passwd2 ' http://localhost:8080/login use token to get resources curl-h ' Authorization:your_ Token ' http://localhost:8080/me
The test results are very satisfactory.
But the individual found a few problems or inadequate
1, using PYJWT each time token is generated the same?
2,token should there be time-lapse?
3, now just get token, then token of authority authentication?
Python Bottle Token-based authentication application