It appears that enable_cors=True
hard codes
Access-Control-Allow-Headers
= Content-Type
only!
You cannot override this (for example) with:
anvil.server.HttpResponse().headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
.
to allow additional headers.
So preflight OPTIONS calls from a Get (and I assume Post etc) with Basic Auth will fail as the Authorization Header is not allowed.
The solution (for me at least) was to remove the enable_cors=True
from the endpoint decorator and set the CORS headers manually.
Here is my final (proof of concept) endpoint:
@anvil.server.http_endpoint('/auth_user/',methods=["GET", "OPTIONS"])
def auth_user():
print(anvil.server.request.method)
if anvil.server.request.method == 'OPTIONS':
r = anvil.server.HttpResponse()
r.headers['Access-Control-Allow-Origin'] = '*'
r.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
r.headers['Access-Control-Request-Method'] = '*'
r.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
print(r.headers)
return r
else:
print("Username", anvil.server.request.username)
print("Password", anvil.server.request.password)
user = app_tables.users.get(email=anvil.server.request.username)
if user is not None and bcrypt.checkpw(anvil.server.request.password.encode('utf-8'), user['password_hash'].encode('utf-8')):
cu_tm_ref = user['tm_ref']
cu_email = user['email']
else:
cu_tm_ref = ''
cu_email = 'Login Failed'
result = {'tm_ref': cu_tm_ref, 'email': cu_email}
r = anvil.server.HttpResponse(200, result)
r.headers['Access-Control-Allow-Origin'] = '*'
r.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
r.headers['Access-Control-Request-Method'] = '*'
r.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
print(anvil.server.HttpResponse())
return r
This is all new to me so I may be trying to fix something that I should have done differently to begin with - but it works!