
在现代浏览器中进行验证码功能的替代方法
随着 samesite 属性的引入,通过 cookie 实现验证码功能遇到了挑战。为了应对这些困难,以下是一种不需要 cookie 的替代方法:
方法:
- 发送验证码请求:前端调用发送验证码的接口,该接口向用户指定的手机号发送一个验证码。
- 存储验证码:与此同时,该接口将验证码暂时存储在 redis中,设置一个有效的期限(例如 1 分钟)。
- 不要返回验证码:验证码不返回给前端。
- 验证请求:当用户通过手机收到验证码后,用户可以手动输入验证码并调用验证接口。该接口会获取用户输入的验证码并与 redis 中存储的验证码对比。
优点:
- 不使用 cookie,避免了 samesite 或 cors 引起的问题。
- 验证码只在有限时间内存储,提供了保障。
- 易于实现和使用。
示例实现:
from flask import Flask, request, jsonify
app = Flask(__name__)
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
@app.route('/send_code', methods=['POST'])
def send_code():
phone_number = request.json['phone_number']
code = generate_random_code() # 生成一个随机验证码
redis_client.setex('code:{}'.format(phone_number), 600, code)
return jsonify({})
@app.route('/verify', methods=['POST'])
def verify():
phone_number = request.json['phone_number']
code = request.json['code']
saved_code = redis_client.get('code:{}'.format(phone_number))
if saved_code and saved_code == code.encode('utf-8'):
return jsonify({'verified': True})
return jsonify({'verified': False})
if __name__ == '__main__':
app.run(debug=True)以上方法提供了一种不需要 cookie 的替代方法来实现验证码功能,解决了 samesite 兼容性和 cors 问题。










