Python Learning Notes (6)---OAuth2.0

Source: Internet
Author: User
Tags base64 hmac oauth

OAuth: (Open License)


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6E/BF/wKiom1WEMbKC3Nb5AAIMnP63WMs308.jpg "title=" Qq20150619231328.jpg "alt=" Wkiom1wembkc3nb5aaimnp63wms308.jpg "/>

The authorization mode for OAuth:

    • Authorization Code mode: The most complete function, the most rigorous process

    • Simple code mode: no third-party application server, directly in the browser to the authentication server to request instructions

    • Password mode: User provides user name and password to client

    • Client mode:



OAuth Authorization Server:

in LOGINDEMO.P Added in Y:

#!/usr/bin/env python# -*- coding: utf-8 -*-import base64import  Randomimport timefrom flask import flask, request, redirectapp = flask (__name__) users = {     "xxxx":  ["xxxxx"]}auth_code = {}redirect_ Uri= ' Http://localhost:5000/client/passport ' #  add account to User client_id =  ' xxxxxx ' users[client_id] =  []#  the authorization server needs to save the redirect Urioauth_redirect_uri = []def gen_token (UID):     token = base64.b64encode (': ') join ([STR (UID),  str (Random.random ()),  str (Time.time ()  + 7200)])     users[uid].append (token)     return token #  Generate Authorization Code: Def gen_auth_code (URI):     code = random.randint (0, 10000 )     auth_code[code] = uri    return codedef  Verify_token (token):   &NBsp; _token = base64.b64decode (token)     if not users.get (_ Token.split (': ') [0]) [ -1] == token:        return -1     if float (_token.split (': ') [-1])  >= time.time ():         return 1    else:         return 0@app.route ('/',  methods=[' GET ') Def index ():     print  request.headers    return  ' Hello ' @app. Route ('/login ',  methods=[' GET ') def  login ():     uid, pw = base64.b64decode (request.headers[' Authorization '].split ('   ') [-1]). Split (': ')     if users.get (UID) [0] == pw:         return gen_token (UID)     else:         return  ' ERROR ' #授权码的发放: @app. Route ('/oauth ',  methods=[' GET ') Def oauth ():     #  Verify user authorization     if request.args.get (' user '):         if users.get (request.args.get (' user ')) [0] == request.args.get (' PW ')  and  oauth_redirect_uri:            uri =  oauth_redirect_uri[0] +  '? code=%s '  % gen_auth_code (oauth_redirect_uri[0])              return redirect (URI)      if request.args.get (' code '): #  if the request carries an authorization code,         #  uri        if auth_code.get (int (request.args.get (' Code ') ))  == request.args.get (' Redirect_uri '):             return gen_Token (request.args.get (' client_id ')) #  issued Token    if request.args.get (' Redirect_ Uri '):         oauth_redirect_uri.append (Request.args.get (' Redirect_uri ')     return  ' please login ' #  redirect #  user access to the client's login directory, The client redirects the user to the authorized server Oauth@app.route ('/client/login ',  methods=[' GET ') def client_login ():     uri =  ' http://localhost:5000/oauth?response_type=code&client_id=%s&redirect_uri= %s '  %  (        client_id, redirect_uri)      return redirect (URI) @app. Route ('/client/passport ',  methods=[' POST ',  ' GET ']) def  client_passport ():     code = request.args.get (' Code ')      uri =  ' http://localhost:5000/oauth?grant_type=authorization_code&code=%s&redirect_uri= %s&client_id=%s '  %  (code, redirect_uri, client_id)     return redirect (URI) @app. Route ('/test1 ',  methods =[' GET ']) def test ():     token = request.args.get (' token ')      if verify_token (token)  == 1:        return  ' Data '     else:        return  ' ERROR ' if _ _name__ ==  ' __main__ ':     app.run (debug=true)


In requests_t.py

#!/usr/bin/env python#-*-coding:utf-8-*-import requestsr = requests.get (' http://localhost:5000/client/login ') print R.textprint R.historyprint r.urluri_login = R.url.split ('? ') [0] + '? User=zx&pw=thystar ' r2 = requests.get (uri_login) Print r2.textr = Requests.get (' Http://127.0.0.1:5000/test1 ', params={' token ': R2.text}) Print R.text




Flask render page Set cookies;

How to encrypt cookies:

Changes to the source code:

logindemo.py

#!/usr/bin/env python# -*- coding: utf-8 -*-import base64import  randomimport timeimport jsonimport hmacfrom datetime import datetime,  timedeltafrom flask import flask, request, redirect, make_responseapp =  flask (__name__) users = {     "ZX":  ["Thystar"]}redirect_uri= '/http Localhost:5000/client/passport ' client_id =  ' Thystar ' users[client_id] = []auth_code =  {}oauth_redirect_uri = []TIMEOUT = 3600 * 2#  new version of the token generator Def gen _token (data):     "    :p aram data: dict type     :return: base64 str     '     data =  data.copy ()     if  "Salt"  not in data:         data["Salt"]&nbsP;= unicode (Random.random ()). Decode ("ASCII")     if  "expires"  not in  data:        data["Expires"] = time.time ()  +  timeout    payload = json.dumps (data) encode ("UTF8")      #  Generate signature     sig = _get_signature (payload)     return  encode_token_bytes (PAYLOAD&NBSP;+&NBSP;SIG) #  Authorization Code generator Def gen_auth_code (uri, user_id):     code = random.randint (0,10000)     auth_code[code] =  [uri, user_id]    return code#  new version of token verification Def verify_token (token):      "    :p aram token: base64 str     :return: dict type     '     decoded_token =  decode_token_bytes (str (token))     payload = decoded_token[:-16]    sig =  decoded_token[-16:]    #  Generating Signature     expected_sig = _get_ Signature (payload)     if sig != expected_sig:         return {}    data = json.loads (Payload.decode ("UTF8"))     if data.get (' Expires ')  >= time.time ():         return data    return 0#  using HMAC to generate signatures for messages def _get_ Signature (value):     "" "Calculate the hmac signature for the  given value. "" "     return hmac.new (' secret123456 ',  value). Digest () #  The following two functions encapsulate Base64 encoding and decoding separately Def encode_token_bytes (data):     return base64.urlsafe_ B64encode (data) Def decoDe_token_bytes (data):     return base64.urlsafe_b64decode (data) #  Verify server-side @app.route ('/index ',  methods=[' POST ',  ' GET ']) def index ():    print  request.headers    return  ' Hello ' @app. Route ('/login ',  methods=[' POST ',  ' GET ']) Def login ():     uid, pw = base64.b64decode (request.headers[') Authorization '].split ('   ') [-1]). Split (': ')     if users.get (UID) [0] ==  Pw:        return gen_token (Dict (USER=UID,&NBSP;PW=PW))      else:        return  ' ERROR ' @app. Route ('/oauth ',  methods=[' POST ',  ' GET ']) Def oauth ():    #  process form login,  set cookies at the same time     if request.method ==  ' POST '  and request.form[' user ']:         u = request.form[' user ']        p = request.form [' PW ']        if users.get (u) [0] == p and  oauth_redirect_uri:            uri =  oauth_redirect_uri[0] +  '? code=%s '  % gen_auth_code (oauth_redirect_uri[0], u)              expire_date = datetime.now ()   + timedelta (Minutes=1)             resp =  make_response (redirect (URI))              Resp.set_cookie (' Login ',  ' _ '. Join ([u, p]),  expires=expire_date)              return resp    #  Verify Authorization code, issue token     if rEquest.args.get (' Code '):         auth_info = auth_code.get ( Int (request.args.get (' Code ')))         if auth_info[0] ==  request.args.get (' Redirect_uri '):             #  can store the user name in the Auth_code of the authorization code, into token              return gen_token (Dict (Client_id=request.args.get (' client_id '),  user_id=auth_info[1])      #  if the logged-in user has a cookie, the direct verification is successful, otherwise you need to fill in the login form     if request.args.get (' Redirect_uri '):         oauth_redirect_uri.append (Request.args.get (' Redirect_uri ')         if request.cookies.get (' login '):             u, p = request.cookies.get (' Login '). Split ('_')              if users.get (U) [0] == p:                 uri = oauth_ redirect_uri[0] +  '? code=%s '  % gen_auth_code (oauth_redirect_uri[0], u)                  return redirect (URI)         return  '              <form action= ""  method= "POST" >                 <p><input type=text name= User>                <p ><input type=text name=pw>                 <p><input type=submit value=login>             </form>         ' #  client @app.route ('/ Client/login ',  methods=[' POST ',  ' GET ']) def client_login ():     uri =   ' http://localhost:5000/oauth?response_type=code&client_id=%s&redirect_uri=%s '  %  ( Client_id, redirect_uri)     return redirect (URI) @app. Route ('/client/passport ',  methods=[' POST ',  ' GET ']) def client_passport ():    code =  Request.args.get (' code ')     uri =  ' http://localhost:5000/oauth?grant_type= authorization_code&code=%s&redirect_uri=%s&client_id=%s '  %  (Code, redirect_uri,  client_id)     return redirect (URI) #  resource server-side @app.route ('/test1 ',  methods=[' POST ',  ' GET ']) def test (): &nbsP;   token = request.args.get (' token ')     ret = verify_ Token (token)     if ret:        return  Json.dumps (ret)     else:        return  ' ERROR ' if __name__ ==  ' __main__ ':     app.run (debug=true)



Run Http://localhost:5000/client/login

Login to get token, put token into test1 test









Geek College: http://www.jikexueyuan.com/course/695.html


Python Learning Notes (6)---OAuth2.0

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.