0
0
Rest APIprogramming~5 mins

Bearer token authentication in Rest API

Choose your learning style9 modes available
Introduction

Bearer token authentication helps keep your app safe by checking if a user has permission to access certain data or actions.

When you want to let users log in once and use the app without typing their password again.
When your app talks to another app or service and needs to prove it has permission.
When you want to protect private data so only the right users can see it.
When you build APIs that many different apps or devices will use securely.
Syntax
Rest API
Authorization: Bearer <token>
The token is a secret string that proves who you are.
It is sent in the HTTP header named 'Authorization'.
Examples
A simple example where 'abc123xyz' is the token sent to the server.
Rest API
Authorization: Bearer abc123xyz
A longer token, often a JWT (JSON Web Token), used for more secure authentication.
Rest API
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Sample Program

This Python program sends a GET request to an API with a bearer token in the header. It prints the status code and the response body.

Rest API
import requests

url = 'https://api.example.com/data'
token = 'abc123xyz'
headers = {'Authorization': f'Bearer {token}'}

response = requests.get(url, headers=headers)
print('Status code:', response.status_code)
print('Response body:', response.text)
OutputSuccess
Important Notes

Never share your bearer token publicly; it is like a password.

Tokens usually expire after some time for safety.

Always use HTTPS to keep tokens safe during transfer.

Summary

Bearer tokens are secret keys sent in the Authorization header.

They help servers know who you are and what you can do.

Use them to keep your app and data secure.