I have a website which uses Token-based authentication. At first, username and password are sent to log the user in and receive the token. For subsequent calls, I need to include the token as X-Auth-Token
in HTTP header.
I would like to know how to do that, in vanilla JavaScript or using jQuery. Could you please provide me a sample of code?
To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.
To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.
In JWT token authentication, the server-provided token should always be sent as a header with the Authorization: Bearer <token> format. The website then should check the validity of the token when a request comes and handle it accordingly. Yes, the use of HTTPS is mandatory.
This is common practice with authorization methods like OAuth. The API can authorize the request before accepting the contents. This can save some processing overhead by not accepting request that have not been validated by their headers.
In jQuery it would be something like this:
$.ajax({
url : myurl,
headers: {
'X-Auth-Token' : token
});
More details on what you can do with $.ajax()
are in the docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With