问题描述
我是 Flask 和 React 的新手。
我对如何让授权令牌注销感到困惑。
在 Postman 上,我可以很好地注册/登录/注销用户。
但是当涉及到从前端获取标头 Authentication 'Bearer' 时,我发现我被卡住了。
到目前为止,这是我尝试获取授权时得到的结果。
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',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
注销API:
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)),'message': resp
}
return make_response(jsonify(responSEObject)),401
else:
responSEObject = {
'status': 'fail','message': 'Provide a valid auth token.'
}
return make_response(jsonify(responSEObject)),403
初来乍到,我真的相信我在某个地方犯了一个愚蠢的错误
邮递员一切正常,唯一的问题是前端注销!
非常感谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)