嗨,所以我在html按钮的onclick动作后发出了一个休息请求。我在表格中输入了错误的信息,无论如何我总是得到200条响应代码。当我使用终端中的节点测试相同的确切功能时,我应该得到401,所以我知道这不是我编写的api中的问题。
此处是该网络应用的代码;
<button id="loginButton" onclick="login_user()">login</button>
<script type="text/javascript">
function login_user() {
let path = "http://127.0.0.1:5000/api/resource";
let user_input = document.getElementById("user").value;
let pass_input = document.getElementById("pass").value;
let data = {username: user_input, password: pass_input};
fetch(path, {
headers: {
"Content-Type": "application/json"},
method: "POST",
body: JSON.stringify(data)}
).then((response) => {
if (response.status == 200) {
window.location.href = "http://127.0.0.1:5000/welcome"
} else if (response.status == 401) {
window.location.href = "http://127.0.0.1:5000/login"
}
});
};
</script>
即使在登录表单中输入了错误的信息,这里发生的事情也仍然有效,我总是得到200,因此总是重定向到欢迎屏幕。
与此同时,我正在用node测试相同的代码;
const fetch = require("node-fetch");
function login_user(user, pass) {
let path = "http://127.0.0.1:5000/api/resource";
let username = user;
let password = pass;
let data = {username: username, password: password};
fetch(path, {
headers: {
"Content-Type": "application/json"},
method: "POST",
body: JSON.stringify(data)}
).then((response) => {
console.log(response);
if (response.status == 200) {
console.log("success")
}
else {
console.log("failure")
}
});
};
login_user("invalidusername", "invalidpassword")
,这将返回401。有谁知道为什么会这样?
服务器端(瓶),以防此处出现问题:
# initialize app
app = Flask(__name__)
app.config['SECRET_KEY'] = urandom(24)
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///db.sqlite"
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
# extensions
db = SQLAlchemy(app)
auth = HTTPBasicAuth()
class User(db.Model):
'''secure:
-- stores password hash
-- option to auth via token after initial sign in'''
__tablename__ = "users"
# columns
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(32), index=True)
password_hash = db.Column(db.String(64))
email = db.Column(db.String(320))
sign = db.Column(db.String(24))
def hash_password(self, password):
self.password_hash = pwd_context.encrypt(password)
def verify_password(self, password):
return pwd_context.verify(password, self.password_hash)
def generate_auth_token(self, expiration=600):
s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
return s.dumps({'id': self.id})
@staticmethod
def verify_auth_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except SignatureExpired:
return None
except BadSignature:
return None
user = User.query.get(data['id'])
return user
@auth.verify_password
def verify_password(username_or_token, password):
# use token (preferred)
user = User.verify_auth_token(username_or_token)
# use username
if not user:
user = User.query.filter_by(username=username_or_token).first()
if not user or not user.verify_password(password):
return False
g.user = user
return True
@app.route('/api/users', methods=['POST'])
def new_user():
username = request.json.get('username')
password = request.json.get('password')
email = request.json.get('email')
sign = request.json.get('sign')
# missing arguments
if None in (username, password, email, sign):
print('missing arguments')
abort(400)
# username taken
elif User.query.filter_by(username=username).first() is not None:
print('username taken')
abort(400)
# email already registered
elif User.query.filter_by(email=email).first() is not None:
print('email taken')
abort(400)
else:
user = User(username=username, email=email, sign=sign)
user.hash_password(password)
db.session.add(user)
db.session.commit()
return (jsonify({'username': user.username,
'email': user.email, 'sign': user.sign}), 201,
{'Location': url_for('get_user', id=user.id,
_external=True)})
@app.route('/api/users/<int:id>')
def get_user(id):
user = User.query.get(id)
if not user:
abort(400)
return jsonify({
'username': user.username,
'email': user.email,
'sign': user.sign})
@app.route('/api/token')
@auth.login_required
def get_auth_token():
token = g.user.generate_auth_token(600)
return jsonify({'token': token.decode('ascii'), 'duration': 600})
@app.route('/api/resource', methods=['POST'])
@auth.login_required
def get_resource():
return jsonify({
'username': g.user.username,
'email': g.user.email,
'sign': g.user.sign})
if __name__ == '__main__':
if not path.exists('db.sqlite'):
db.create_all()
app.run()