This is a demo of jwt authorization in Express.
Register new user
Requires 3 parameters (in body):
username: string
email: string
password: string
Request body example:
{
"username": "John Doe",
"email": "email@example.com",
"password": "qwerty123"
}
Response body includes following parameters:
username: string
- username specified in request bodyemail: string
- email specified in request bodyrole: 'user'
- user role
Note that this endpoint does not allow to create admin user, you can create admin account in MongoDB client
Also, server sets http-only cookie jwt
with generated token.
If there is an account with same username
or email
, server responds with status 400.
Server response example:
{
"username": "John Doe",
"email": "email@example.com",
"role": "user"
}
Login into existing account
Requires password and either username or email:
username: string (optional)
email: string (optional)
password: string
Request body example:
{
"username": "John Doe",
"password": "qwerty123"
}
or
{
"email": "email@example.com",
"password": "qwerty123"
}
Response body includes following parameters:
username: string
- username specified when registeredemail: string
- email specified when registeredrole: 'user' | 'admin'
- user role
Server sets http-only cookie jwt
with generated token.
If account is not created yet, server responds with status 400. Same happens if required fields (in body) are not provided.
Server response example:
{
"username": "John Doe",
"email": "email@example.com",
"role": "user"
}
Logout from account
No parameters required
Server deletes cookie jwt
and respond with status 200.
Returns array of all users.
No parameters required in body, but jwt is required.
Response body is array of users
Server response example:
[
{
"username": "John Doe",
"email": "email@example.com",
"role": "user"
},
{
"username": "Jane Doe",
"email": "another@example.com",
"role": "admin"
}
]
If token is not provided (user is not authenticated) or user role (which is determined by token) is not 'admin'
, server responds with status 403.
Clone this repository
git clone https://github.com/shelepuginivan/express-jwt-auth.git
cd shrinker
Setup config file
cp .env.example .env
vi .env
Build the project
npm install
npm run build
Run server
npm start