Python Bottle Token-based authentication application

Source: Internet
Author: User
Tags mongodb save

    • #JWT

‘‘‘
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)

‘‘‘

    • Python JWT

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

    • Practice

Save user data with MongoDB

Use bottle to do the service

    1. config.py
Class settings (object):    host = ' localhost '    port = 12306    secret = B '---------00000??? \\‘

  

    1. MongoDB Save Data
User ={    ' name ': ' User1 ',    ' passwd ': ' passwd ',    ' ident ': 0 #public}admin = {    ' name ': ' Bottle ',    ' passwd ': ' passwd2 ',    ' ident ': 1 #admin}
    1. /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
    1. login_required Verification
 def login_required (): Def decorator (func): Def wrapper ( *args, **kwargs): Authorization  = request.headers. get  ( "  '   '  if  
  returnreturn decorator
    1. /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

    • Test

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

  

    • Summarize

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.