I am developing a Flask application which gives call to the REST service developed in Flask. The target REST service method is secured using Basic Authentication. I found that for this type of authentication, I have to use base64 encoding. I am trying to pass the credentials to the service in this way:
headers = {'username': base64.b64encode(g.user['username'])}
response = requests.post('http://127.0.0.1:3000/api/v1.0/follower/' + username, headers=headers)
And at the service side, the username is fetched as :
user_name = request.authorization.username
However, the service is not able to authorize the provided credentials and it is throwing an error 401. Is there any issue with the authorization at the service side and at the application side?
You are not creating a proper Basic Authorization header.
You'd have to call the header Authorization
, and then set the header value to the string Basic <base64-of-username-and-password-separated-by-a-colon>
.
If we assume an empty password, that would look like:
headers = {
'Authorization': 'Basic {}'.format(
base64.b64encode(
'{username}:{password}'.format(
username=g.user['username'],
password='')
)
),
}
See the Wikipedia description of the client side of the protocol.
However, there is no need to construct this manually, as requests
will create the header for you when you pass in a username and password as a tuple to the auth
keyword:
response = requests.post(
'http://127.0.0.1:3000/api/v1.0/follower/' + username,
auth=(g.user['username'], ''))