Flask认证:token

本文详细介绍了使用Python和Flask框架实现用户认证的方法,包括基于token的认证和密码认证。通过werkzeug和itsdangerous库,实现了密码的加密存储和token的生成验证,确保了用户信息的安全。
摘要由CSDN通过智能技术生成

1 认证方法

  • token认证
  • 密码认证

2 Usage

2.1 Authentaion.py

from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer 
from itsdangerous import BadSignature, SignatureExpired
from app import app

app.config["SECRET_KEY"] = "123456"
methods = ["pbkdf2:sha256", "pbkdf2:sha256:1200"]
class AuthToken(object):
    @staticmethod
    def generate_auth_token(expiration=60):
        s = Serializer(app.config["SECRET_KEY"], expires_in=expiration)
        return s.dumps({"id":250})
    @staticmethod
    def verify_auth_token(token):
        s = Serializer(app.config["SECRET_KEY"])
        try:
            data = s.loads(token)
        except SignatureExpired:
            return False
        except BadSignature:
            return False
        # user = User.query.get(data["id"])
        return True

class VerifyPassword(object):
    @staticmethod
    def set_password(password):
        hash_pwd = generate_password_hash(password, method=methods[0])
        return hash_pwd

    @staticmethod
    def check_password(hash_pwd, password):
        return check_password_hash(hash_pwd, password)

2.2 token

from flask import Flask, Blueprint, jsonify, request, g, abort
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer 
from itsdangerous import BadSignature, SignatureExpired
from flask_httpauth import HTTPBasicAuth
from utils.AuthToken import AuthToken


from flask_sqlalchemy import SQLAlchemy 
from app.models.databases import User
from app import app, db, manager 
from werkzeug.security import generate_password_hash, check_password_hash

token_tests = Blueprint("token_test", __name__, url_prefix="/api")

@token_tests.route("/token-get", methods=["GET", "POST"])
def get_data():
    token = AuthToken.generate_auth_token(expiration=60)
    return jsonify({"token":token, "code":200})

@token_tests.route("/token-validate", methods=["GET", "POST"])
def validate_token():
    token = request.headers["X-AuthToken"]
    token_status = AuthToken.verify_auth_token(token)
    if token_status:
        return jsonify({"infos":"token valid"})
    else:
        return jsonify({"infos":"token invalid"})
def init_app():
    # app = Flask(__name__)
    app.config["SECRET_KEY"] = "123456"
    app.register_blueprint(token_tests)

    return app 
app = init_app()

if __name__ == "__main__":
    db.create_all()
    app.run(host="0.0.0.0", port=8090, debug=True)

2.3 password

  • databases.py
from app import db, app
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer 
from itsdangerous import BadSignature, SignatureExpired
from flask import jsonify

app.config["SECRET_KEY"] = "123456"
methods = ["pbkdf2:sha256", "pbkdf2:sha256:1200"]
salt_length = [4, 5, 7]

class User(UserMixin, db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(320), unique=False, nullable=False)
    password = db.Column(db.String(320), unique=False, nullable=False)

    def set_password(self, password):
        self.password = generate_password_hash(password, method=methods[0])

    def check_password(self, hash_pwd, password):
        return check_password_hash(hash_pwd, password)
from flask import Flask, Blueprint, jsonify, request, g, abort
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer 
from itsdangerous import BadSignature, SignatureExpired
from flask_httpauth import HTTPBasicAuth
from utils.AuthToken import AuthToken


from flask_sqlalchemy import SQLAlchemy 
from app.models.databases import User
from app import app, db, manager 
from werkzeug.security import generate_password_hash, check_password_hash

token_tests = Blueprint("token_test", __name__, url_prefix="/api")

@token_tests.route("/create-user", methods=["GET", "POST"])
def create_user():
    username = request.json["username"]
    password = request.json["password"]
    if username is None or password is None:
        abort(400)
    if User.query.filter_by(name=username).first() is not None:
        abort(400)
    user = User(name=username)
    user.set_password(password)
    # db.sessoin.add_all([user])
    db.session.add(user)
    db.session.commit()
    return jsonify({"info":{"username":user.name, "id":user.id}, "code":200})
    
@token_tests.route("/user/validate-pwd", methods=["GET", "POST"])
def user_validate_pwd():
    username = request.json["username"]
    password = request.json["password"]
    user = User.query.filter_by(name=username).first()
    print("user info: {}".format(user))
    user_status = user.check_password(user.password, password)
    if user_status:
        return jsonify({"info":"Legal user", "code":200})
    else:
        return jsonify({"info":"ILegal user", "code":201})
def init_app():
    # app = Flask(__name__)
    app.config["SECRET_KEY"] = "123456"
    app.register_blueprint(token_tests)

    return app 
app = init_app()

if __name__ == "__main__":
    db.create_all()
    app.run(host="0.0.0.0", port=8090, debug=True)

【参考文献】
[1]https://www.cnblogs.com/vovlie/p/4182814.html
[2]https://blog.csdn.net/qq_42597385/article/details/85248483
[3]http://www.pythondoc.com/flask-restful/third.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天然玩家

坚持才能做到极致

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值