我是 Flask 和 React 的新手。
我对如何让授权令牌注销感到困惑。
在邮递员上,我可以很好地注册/登录/注销用户。但是当谈到从前端获取标头身份验证“承载”时,我发现我被卡住了。
这是我在尝试获取授权时所得到的。
const [ email, setEmail] = useState('')
const [ password, SetPassword] = useState('')
const onSubmitClick = (e) => {
e.preventDefault()
console.log('You pressed login')
let opts = {
'email': email,
'password': password
}
console.log(opts)
fetch('/auth/login', {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(opts)
}).then(r => r.json())
.then(token => {
if (token.auth_token){
login(token)
console.log(token)
}
else {
console.log("Please type in the correct Email or Password")
}
})
}
const onLogoutClick = (e) => {
fetch('/auth/login', {
method: 'post',
headers: {
'Authorization': `Basic `,
'Content-Type': 'application/json'
},
}).then(r => r.json())
.then(token => {
if (token.auth_token){
login(token)
console.log(token)
}
else {
console.log("Please type in the correct Email or Password")
}
})
}
登录接口:
class LoginAPI(MethodView):
def post(self):
post_data = request.get_json()
try:
user = User.query.filter_by(
email=post_data.get('email')
).first()
if user and bcrypt.check_password_hash(
user.password, post_data.get('password')
):
auth_token = user.encode_auth_token(user.id)
if auth_token:
responseObject = {
'status': 'success',
'message': 'Successfully logged in.',
'auth_token': auth_token.decode()
}
return make_response(jsonify(responseObject)), 200
else:
responseObject = {
'status': 'fail',
'message': 'User does not exist.'
}
return make_response(jsonify(responseObject)), 404
except Exception as e:
print(e)
responseObject = {
'status': 'fail',
'message': 'Try again'
}
return make_response(jsonify(responseObject)), 500
注销接口:
class LogoutAPI(MethodView):
def post(self):
auth_header = request.headers.get('Authorization')
if auth_header:
auth_token = auth_header.split(" ")[1]
else:
auth_token = ''
if auth_token:
resp = User.decode_auth_token(auth_token)
if not isinstance(resp, str):
blacklist_token = BlacklistToken(token=auth_token)
try:
db.session.add(blacklist_token)
db.session.commit()
responseObject = {
'status': 'success',
'message': 'Successfully logged out.'
}
return make_response(jsonify(responseObject)), 200
except Exception as e:
responseObject = {
'status': 'fail',
'message': e
}
return make_response(jsonify(responseObject)), 200
else:
responseObject = {
'status': 'fail',
'message': resp
}
return make_response(jsonify(responseObject)), 401
else:
responseObject = {
'status': 'fail',
'message': 'Provide a valid auth token.'
}
return make_response(jsonify(responseObject)), 403
作为新手,我真的相信我在某个地方是一个愚蠢的错误
邮递员一切正常,唯一的问题是前端注销!
非常感谢!