Cherry
Cherry

Reputation: 33608

Does it needs to pass username:password combination in any request with basic auth?

I confused with basic http authorization. It is needed to send every request to server with Authorization header or just first one and after that browser rember auth tokens like session id?

Upvotes: 4

Views: 3449

Answers (3)

MvdD
MvdD

Reputation: 23496

Using basic authentication, every request needs to have an Authorization HTTP header in the format:

Authorization: Basic <base64(username:password)>

where the username and password are concatenated using a colon (':') and the resulting string is base64 encoded.

If the Authorization header is not part of the request, or the credentials inside are not valid, the server should respond with an HTTP 401 Unauthorized response and include a HTTP header like:

WWW-Authenticate: Basic realm="myRealm"

Basic authentication is an implicit authentication scheme, so after the user enters valid credential, the browser will send them along with each page request.

For AJAX requests you'll need to attach this header from code. However, you really should not use basic authentication to protect an API, for a number of reasons:

  1. You'd force the client to hold those credentials in code, where they can easily be stolen.
  2. You must use HTTPS with basic authentication as base64 encoding gives no protection of the credentials at all.
  3. Username/password combinations are usually valid much longer than an access token, thereby increasing the risk if they get stolen.
  4. Password validation should be a slow process to mitigate brute force attacks, where token validation is just verifying a digital signature.
  5. Having to send the username/password over the wire every time increases the attack surface for someone trying to break the encryption.

Better alternatives to protect web APIs are token based authentication schemes like OAuth2 or HMAC based authentication schemes like Hawk or AWS

Upvotes: 2

Aishwat Singh
Aishwat Singh

Reputation: 4459

Ya that's correct , so for first time when user logs in , his credentials are verified against some data , if correct , a auth token is generated.

Auth token is pretty much a self contained entity (which stores some data signed with a key)

this token gets stores at client side(usually along with a refresh token) for all subsequent requests , this token is kept in Authorization header(Bearer+token)

When server receives this token , it decrypts it with the key , which it used earlier to sign that token. And uses that stored data

If that auth token is expired , refresh token comes into play.

some links to begin with On a high level, how does OAuth 2 work? and jwt.io to get the feel of tokens

Upvotes: 0

Sebastian Gnitkowitz
Sebastian Gnitkowitz

Reputation: 66

You have to send the Authorization header on each request. But for example Chrome remembers the auth tokens and sends it automatically on each request.

Upvotes: 2

Related Questions