• Stars
    star
    348
  • Rank 121,840 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created over 6 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Example API that shows how to implement JSON Web Token authentication and authorization with ASP.NET Core 7, built from scratch. Related article: https://medium.com/@evandro.ggomes/json-web-token-authentication-with-asp-net-core-2-0-b074b0cfc870

JWT API

This example API shows how to implement JSON Web Token authentication and authorization with ASP.NET Core 7, built from scratch.

Features

  • User registration;
  • Password hashing;
  • Role-based authorization;
  • Login via access token creation;
  • Refresh tokens, to create new access tokens when access tokens expire;
  • Revoking refresh tokens.

Frameworks and Libraries

The API uses the following libraries and frameworks to deliver the functionalities described above:

How to test

I added Swagger to the API, so we can use it to visualize and test all API routes. You can run the application and navigate to /swagger to see the API documentation:

Swagger

You can also test the API using a tool such as Postman. I describe how to use Postman to test the API below.

First of all, clone this repository and open it in a terminal. Then restore all the dependencies and run the project. Since it is configured to use Entity Framework InMemory provider, the project will run without any problems.

$ git clone https://github.com/evgomes/jwt-api.git
$ cd jwt-api/src
$ dotnet restore
$ dotnet run

Creating users

To create a user, make a POST request to http://localhost:5000/api/users specifying a valid e-mail and password. The result will be a new user with common users permission.

{
	"email": "[email protected]",
	"password": "123456"
}

Creating an user

There are already two pre-defined users configured to test the application, one with common users permission and another with admin permissions.

{
	"email": "[email protected]",
	"password": "12345678"
}
{
	"email": "[email protected]",
	"password": "12345678"
}

Requesting access tokens

To request the access tokens, make a POST request to http://localhost:5000/api/login sending a JSON object with user credentials. The response will be a JSON object with:

  • An access token which can be used to access protected API endpoints;
  • A request token, necessary to get a new access token when an access token expires;
  • A long value that represents the expiration date of the token.

Access tokens expire after 30 seconds, and refresh tokens after 60 seconds (you can change this in the appsetings.json).

Requesting a token

Accessing protected data

There are two API endpoints that you can test:

  • http://localhost:5000/api/protectedforcommonusers: users of all roles can access this endpoint if a valid access token is specified;
  • http://localhost:5000/api/protectedforadministrators: only admin users can access this endpoint.

With a valid access token in hands, make a GET request to one of the endpoints mentioned above with the following header added to your request:

Authorization: Bearer your_valid_access_token_here

If you get a token as a common user (a user that has the Common role) and make a request to the endpoint for all users, you will get a response as follows:

Common user

But if you try to pass this token to the endpoint that requires admin permission, you will get a 403 - forbidden response:

403 Forbidden

If you sign in as an admin and make a GET request to the admin endpoint, you will receive the following content as response:

Admin restricted data

If you pass an invalid token to any of the endpoints (a expired one or a token that was changed by hand, for example), you will get a 401 unauthorized response.

401 Unauthorized

Refreshing tokens

Imagine you have a single page application or a mobile app and you do not want the users to have to log in again every time an access token expires. To deal with this, you can get a new token with a valid refresh token. This way, you can keep users logged in without explicitly asking them to sign in again.

To refresh a token, make a POST request to http://localhost:5000/api/token/refresh passing a valid refresh token and the user's e-mail in the body of the request.

{
	"token": "your_valid_refresh_token",
	"userEmail": "[email protected]"
}

You will receive a new token if the specified refresh token and e-mail are valid:

Refreshing token

If the request token is invalid, you will receive a 400 response:

Invalid refresh token

Revoking refresh tokens

Now imagine that you want the user to sign out, or you want to revoke a refresh token for any reason. You can revoke a refresh token making a POST request to http://localhost:5000/api/token/revoke, passing a valid refresh token into the body of the request.

{
	"token": "valid_refresh_token"
}

You will get a 204 No Content response after calling this endpoint.

Revoking token

Considerations

This example was created with the intent of helping people who have doubts on how to implement authentication and authorization in APIs to consume these features in different client applications. JSON Web Tokens are easy to implement and secure.

If you have doubts about the implementation details or if you find a bug, please, open an issue. If you have ideas on how to improve the API or if you want to add a new functionality or fix a bug, please, send a pull request.

More Repositories

1

supermarket-api

Simple RESTful API built with ASP.NET Core and .NET 8 to show how to create RESTful services using a decoupled, maintainable architecture.
C#
480
star
2

cqrs-mediatr-asp-net-core

Sample ASP.NET Core API that uses MediatR in a CQRS approach to handle requests and responses.
C#
42
star
3

csharp-designpatterns

Design patterns examples applied in real world situations. The intent of this repository is to show how .NET developers can write clean code, easy to maintain, using consolidated patterns to approach common situations while developing softwares..
C#
37
star
4

net-core-event-bus

Sample event bus implementation that uses RabbitMQ as a message broker for high-performance communication between microservices.
C#
22
star
5

tic-tac-toe-angular

Simple tic-tac-toe game built with Angular 6.
TypeScript
4
star
6

chat-node-socket-io

Aplicação simples de chat desenvolvida em Node.js, utilizando Socket.IO para funcionalidade de troca de mensagens em tempo real.
JavaScript
4
star
7

vidly-api

Movie rental API built with Node.js.
JavaScript
4
star
8

calculo-imposto-renda

Aplicação que calcula o imposto de renda de contribuintes, levando em conta o salário mínimo atual e a quantidade de dependentes do contribuinte.
C#
3
star
9

net-core-notes

Sample full-stack .NET application (ASP.NET Core + Blazor) to create and manage sticky notes.
C#
3
star
10

organic-shop

Simple e-commerce application built with Angular, Firebase and Bootstrap 4. Demo: https://oshop-25cf2.firebaseapp.com/
TypeScript
3
star
11

logging-to-api

Sample ASP.NET 6 application that sends log data to a RESTful API.
C#
2
star
12

notes-redux

Sample React + Redux application.
JavaScript
2
star
13

seguradora

Aplicação de exemplo em ASP.NET Core para gerenciar uma empresa de seguros.
C#
2
star
14

cervejaria-angular

Aplicação de testes em Angular 8 para controle de uma cervejaria.
TypeScript
2
star
15

react-task-management

Simple task management application built with React.js.
JavaScript
2
star
16

smart-sorting

Sort algorithms library to use with .NET Standard.
C#
1
star
17

react-context-api

Sample React application that uses the React Context API to manage state.
JavaScript
1
star
18

express-file-upload-api

Simple API built with Express.js and Multer to show how to handle file upload throught the use of simple middlewares.
JavaScript
1
star
19

flashcards

A flashcard app made with React-Native and Redux
JavaScript
1
star
20

gestao-de-pedidos

Sistema para gestão de pedidos e anotações referente a revenda de cosméticos.
JavaScript
1
star