[英]401 UNAUTHORIZED status when attempting login from client side to backend flask api
I am trying to login from my website developed in Angular to the back end flask API, The backend uses bcrypt for encoding and pymongo for interacting with a MongoDB. I am trying to login from my website developed in Angular to the back end flask API, The backend uses bcrypt for encoding and pymongo for interacting with a MongoDB. In postman, the login endpoint works fine but when an attempt to log in on the client side is made I receive a 401: UNAUTHORIZED ERROR.
在 postman 中,登录端点工作正常,但是当尝试在客户端登录时,我收到 401:未经授权的错误。 Can someone advise what the issue is/where I am going wrong?
有人可以告诉我问题是什么/我哪里出错了吗?
The login function on the client side:客户端登录function:
onLogin() {
let postData = new FormData();
postData.append('username', this.loginForm.get('username').value);
postData.append('password', this.loginForm.get('password').value);
this.http.post('http://localhost:5000/api/v1.0/login', postData)
.subscribe((_response: any) => {
console.log(this.loginForm.value);
this.loginForm.reset();
})
}
The login endpoint in backend:后端的登录端点:
app = Flask(__name__)
CORS(app)
@app.route('/api/v1.0/login', methods=['POST'])
def login():
auth = request.authorization
if auth:
user = users.find_one({'username': auth.username})
if user is not None:
if bcrypt.checkpw(bytes(auth.password, 'utf-8'),
user["password"]):
token = jwt.encode( \
{'user' : auth.username,
'admin': user["admin"],
'exp' : datetime.datetime.utcnow() + \
datetime.timedelta(minutes=30)
}, app.config['SECRET_KEY'])
return make_response(jsonify( \
{'token':token.decode('UTF-8')}), 200)
else:
return make_response(jsonify( \
{'message':'Bad password'}), 401)
else:
return make_response(jsonify( \
{'message':'Bad username'}), 401)
In order to use request.authorization
you need to send the credentials in the Authorization-header.为了使用
request.authorization
您需要在 Authorization-header 中发送凭据。 Try this on the client:在客户端试试这个:
onLogin() {
const usn = this.loginForm.get('username').value;
const pwd = this.loginForm.get('password').value;
this.http.post('http://localhost:5000/api/v1.0/login', null, {
headers: new HttpHeaders({
Authorization: `Basic ${btoa(`${usn}:${pwd}`)}`
})
}).subscribe((_response: any) => {
console.log(_response);
});
}
As a sidenote;作为旁注; the credentials can be easily decoded by using
atob()
, so make sure you are using a secure connection (HTTPS) when not on localhost.可以使用
atob()
轻松解码凭据,因此请确保您不在本地主机上时使用安全连接 (HTTPS)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.