วิธีการใช้งานตัว flask jwt เพื่อทำการ authenticate แบบใช้ Token ด้วย curl

แชร์ความรู้ภาษา Python ไพทอน การเขียนโปรแกรมภาษาไพทอน

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
jirawoot
PHP VIP Members
PHP VIP Members
โพสต์: 3129
ลงทะเบียนเมื่อ: 17/06/2019 10:30 am

วิธีการใช้งานตัว flask jwt เพื่อทำการ authenticate แบบใช้ Token ด้วย curl

โพสต์ที่ยังไม่ได้อ่าน โดย jirawoot »

วิธีการใช้งานตัว flask jwt เพื่อทำการ authenticate แบบใช้ Token ด้วย curl
สำหรับนักพัฒนาที่กำลังหาวิธีการใช้ authenticate แบบใช้ Token หรือรวมไปถึงการขอ Token เพื่อที่จะนำไปใช้ สำหรับภาษา Python ก็มี Package ตัวหนึ่งมาแนะนำครับ flask_jwt ตัวนี้จะใช้งานควบคู่ไปกับตัว Flask ธรรมดาด้วยให้ทำการดาวน์โหลดตัว Package มาก่อนโดยการใช้คำสั่ง

โค้ด: เลือกทั้งหมด

pip install Flask-JWT
ใช้กับ python 2.7 ได้ เมื่อทำการติดตั้งตัว Package เสร็จแล้วให้ทำการสร้างไฟล์ python ขึ้นมาแล้วทำการ import ตัว Package ทำต้องใช้

โค้ด: เลือกทั้งหมด

from flask import Flask
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp
สร้าง class เพื่อเก็บข้อมูล user

โค้ด: เลือกทั้งหมด

class User(object):
    def __init__(self, id, username, password):
        self.id = id
        self.username = username
        self.password = password

    def __str__(self):
        return "User(id='%s')" % self.id
กำหนด user ทำใช้งาน สามารถดึงข้อมูลมาจาก database ได้

โค้ด: เลือกทั้งหมด

users = [
    User(1, 'test01', 'test1234'),
    User(2, 'test02', 'test6789'),
]

username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
ทำการสร้าง method authenticate และ identity

โค้ด: เลือกทั้งหมด

def authenticate(username, password):
    user = username_table.get(username, None)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user

def identity(payload):
    user_id = payload['identity']
    return userid_table.get(user_id, None)
จากนั้นให้ทำการกำหนด route ของ http และ config ของ flask

โค้ด: เลือกทั้งหมด

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'super-secret'

jwt = JWT(app, authenticate, identity)

@app.route('/helloworld')
@jwt_required()
def helloworld():
    return 'HelloWorld %s' % current_identity

if __name__ == '__main__':
    app.run()
โค้ดรวม

โค้ด: เลือกทั้งหมด

from flask import Flask
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp

class User(object):
    def __init__(self, id, username, password):
        self.id = id
        self.username = username
        self.password = password

    def __str__(self):
        return "User(id='%s')" % self.id

users = [
    User(1, 'test01', 'test1234'),
    User(2, 'test02', 'test6789'),
]

username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}

def authenticate(username, password):
    user = username_table.get(username, None)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user

def identity(payload):
    user_id = payload['identity']
    return userid_table.get(user_id, None)

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'super-secret'

jwt = JWT(app, authenticate, identity)

@app.route('/helloworld')
@jwt_required()
def helloworld():
    return 'HelloWorld %s' % current_identity

if __name__ == '__main__':
    app.run()
ทำการรันโปรแกรม
Python Knowledge-1.png
Python Knowledge-1.png (23.12 KiB) Viewed 1125 times
เปิด terminal ขึ้นมา

โค้ด: เลือกทั้งหมด

curl -d '{"username": "<ใส่ username>","password": "<ใส่ password>" }' -H "Content-Type: application/json" -X POST http://127.0.0.1:5000/auth
ผลที่ได้

โค้ด: เลือกทั้งหมด

{
  "access_token": "<Token ที่ขอไป>"
}

ตัวอย่าง เช่น

โค้ด: เลือกทั้งหมด

$ curl -d '{"username": "test01","password": "test1234" }' -H "Content-Type: application/json" -X POST http://127.0.0.1:5000/auth

โค้ด: เลือกทั้งหมด

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZGVudGl0eSI6MSwiaWF0IjoxNTg4MjQ3NzE0LCJuYmYiOjE1ODgyNDc3MTQsImV4cCI6MTU4ODI0ODAxNH0.EEHYLQFLso7MUMV5FW7IwAVzTXGoduW3Obchvkql46g"
}
เมื่อได้ Token มาแล้วจากให้ทำการ authenticate ด้วย curl

โค้ด: เลือกทั้งหมด

curl -H "Authorization: JWT <Token ที่ได้มา>" http://< hostname>:<port>/helloworld
ตัวอย่าง เช่น

โค้ด: เลือกทั้งหมด

curl -H "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZGVudGl0eSI6MSwiaWF0IjoxNTg4MjQ3NzE0LCJuYmYiOjE1ODgyNDc3MTQsImV4cCI6MTU4ODI0ODAxNH0.EEHYLQFLso7MUMV5FW7IwAVzTXGoduW3Obchvkql46g" http://127.0.0.1:5000/helloworld
ผลที่ได้

โค้ด: เลือกทั้งหมด

HelloWorld User(id='1')

อ้างอิง
https://pythonhosted.org/Flask-JWT/
https://flask-jwt-extended.readthedocs.io/en/stable/
https://medium.com/trabe/user-authentication-with-flask-jwt-be0e6f457dff
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: Google Adsense [Bot] และบุคลทั่วไป 39