How to return 401 authentication from flags API?
I have developed a flask API that uses HttpBasicAuth to authenticate users. The API works fine in fiddler and returns 401 when we pass in the wrong credentials, but when I use the same on the login page, I get an additional popup from the browser. I really don't want to see this additional popup that asks for credentials (browser default behavior when returning
401
from
WWW-Authenticate: Basic realm="Authentication Required"
).
It works fine when deployed locally, but doesn't work when hosted on a remote server.
How can we implement a 401 that will prevent the browser from showing a popup asking for credentials.
source to share
This is a common problem with REST APIs and browsers. Unfortunately, there is no clean way to prevent the browser from displaying the popup. But there are tricks you can do:
-
You can return a non-401 status code. For example, return 403. This is technically wrong, but if you have control over the client API, you can make it work. The browser will only display the login dialog when it receives a 401.
-
Another, maybe slightly clean trick, is to leave 401 in the response, but not include the header
WWW-Authenticate
in your response. This will also stop the login dialog from appearing. -
And another one (which I have not tried myself, but saw that is mentioned elsewhere) should leave 401 and
WWW-Authenticate
but change the auth method fromBasic
to something else, which is unknown to the browser (i.e. notBasic
, notDigest
). For example, do thisCustomBasic
.
source to share
So, the flag return statements are actually processed again before sending data to the client. In fact, you can send a two-tuple as a return statement. the second element is the status ( https://en.wikipedia.org/wiki/List_of_HTTP_status_codes ). If you are using auth library you can change this:
@auth.error_handler
def unauthorized():
response = jsonify({'message':'Failed'})
return response
For this:
@auth.error_handler
def unauthorized():
response = jsonify({'message':'A winner is you'})
return response, 404
If you don't want the popup message, change the 401 value to something else.
source to share