見出し画像

超簡単PythonでWeb API認証(Flask-JWT利用)

Pythonで超簡単にWeb API Authentication(Flask-JWT利用)

1. ツールインストール

$ pip install Flask-JWT

2. ファイル作成

jwt.py

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, "user1", "abcxyz"),
   User(2, "user2", "abcxyz"),
]

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("/protected")
@jwt_required()
def protected():
   return "%s" % current_identity


if __name__ == "__main__":
   app.run()

3. 実行

$ python jwt.py

4. アクセストークン取得

$ curl -X POST -H "Content-Type: application/json" -d '{"username":"user1", "password":"abcxyz"}' localhost:5000/auth

{
 "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjkyNjkwNjQsImlhdCI6MTYyOTI2ODc2NCwibmJmIjoxNjI5MjY4NzY0LCJpZGVudGl0eSI6MX0.54sv2ZLorvjOwgajw5T6P8IaJAwzSfU4JHPmEu8KuvI"
}

5. ヘッダーにアクセストークン指定してリクエスト

$ curl -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjkyNjkwNjQsImlhdCI6MTYyOTI2ODc2NCwibmJmIjoxNjI5MjY4NzY0LCJpZGVudGl0eSI6MX0.54sv2ZLorvjOwgajw5T6P8IaJAwzSfU4JHPmEu8KuvI" localhost:5000/protected

User(id='1')

以上、超簡単!

6. 参考


いいなと思ったら応援しよう!