git clone https://github.com/bariyer/express-bearer-auth-example.git
npm i
yarn
mv .env.example .env
Example:
# –––------------ JSON Web Token –––------------
# Your JWT Secret Key. This key is unique to you. Please don't share with anyone.
# Its could be anything. Ex. example_secret_key
JWT_SECRET_KEY=9a20452f-dcc1-5b2f-95b0-8a6d167e178a
# format being https://github.com/vercel/ms
JWT_EXPIRE=1d
# format being https://github.com/vercel/ms
JWT_COOKIE_EXPIRE=2d
yarn start
npm start
4. Open Postman or similar tool to test the API
- Click import button
- Select
Link
tab - Paste this link https://www.getpostman.com/collections/db123cb580f6e775853e
- Run the bearer auth requests
Method | Endpoint | Headers | Body |
---|---|---|---|
GET |
http://localhost:3001/ | Authorization: Bearer <access_token> |
{} |
Response Code: 200 OK
Response Body:
[
{
"id": 1,
"name": "Milk"
},
{
"id": 2,
"name": "Cheese"
}
]
Method | Endpoint | Headers | Body |
---|---|---|---|
POST |
http://localhost:3001/login | Authorization: Bearer <access_token> |
x-www-form-urlencoded {username: john, password: 123456} |
Response Code: 200 OK
Response Body:
{
"access_token": "<your_access_token>"
}
Response Code: 401 Unauthorized
Response Body:
{
"message": "username or password incorrect"
}
Method | Endpoint | Headers | Body |
---|---|---|---|
POST |
http://localhost:3001/register | Authorization: Bearer <access_token> |
x-www-form-urlencoded {username: john, password: 1234567} |
Response Code: 200 OK
Response Body:
{
"id": "eka031pkt6e9p43nzv50yntp",
"username": "john",
"password": "$2b$10$.jLwU8c0v8ICv16.zCFhce1A9rggQOsBlENjBuH0VxUKeay3q9xBy"
}
Response Code: 401 Unauthorized
Response Body:
{
"message": "user already registered, go to login"
}
-
If get an error, feel free to open issue.
-
If you have any questions, feel free to open discussion.
Contributions are what make the open source community such an amazing place to be inspire, and create. Any contributions you make are greatly appreciated.
- Fork the Project
- Create your Feature Branch (
git checkout -b feat/AmazingFeature
) - Commit your Changes (
git commit -m 'Add some AmazingFeature'
) - Push to the Branch (
git push origin feat/AmazingFeature
) - Open a Pull Request
Distributed under the MIT License. See LICENSE
for more information.