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