.NET Jwt Authentication with MongoDB

Filip Tonic
Nerd For Tech

--

Hello everyone! In this tutorial I will show you a way to implement JWT Authentication but in this case using MongoDB driver.

First we will create new web api using dotnet cli. Open your terminal and run command: dotnet new webapp - -name=webapi.
This will create start boilerplate for our application.

Open the crafted application in your favorite code editor, I am using vs-code.
This is what you’ll get.

We will start by adding MongoDB Driver package to our application, so we can work with our collections.
In you terminal run: dotnet add package MongoDB.Driver
After installing, get back to project and open your .csproj file, and you should see:
<PackageReference Include=”MongoDB.Driver” Version=”2.12.0" />

Now we are ready to connect to our Mongo database.

In project root create folder Database inside add two files:
1) IDatabaseSettings.cs

2) DatabaseSettings.cs

Please note that namespace will vary on your project name.

In general we need these above 3 information to describe our connection to Database, as well as collection itself. In real life, we will keep these in some sort of environment file.

Now open your Startup.cs file, and navigate to ConfigureServices method and add this line:

Now to specify you connection data, open your appsettings.json and ConnectionString object like so:

If you need, you would add additional info in this file.
We are now done with the connecting to database. Now let’s add some data and read some data from it.
For this purpose I will create Users collection and along with that we will have User model and User Controller in our .Net application.

In root of your project add folder Models. Inside create User.cs file.
For purpose of this article we will keep things simple, and have Email and Password fields.

After this we will separate so called data layer of logic, by creating service class, which will communicate with database, afterwards we will only call its methods in our UserController, which will represent business layer of logic (Your interviewers will love you when you tell ’em this! :D ).

Again in root of you project, create Services folder, and inside UserService.cs file.

For purpose of this tutorial we will only perform some of CRUD operations.
Note that here we are hardcoding collection name etc.
Like I mentioned, in real life you’d be getting these from appsettings.json file.

Now let’s add CRUD operations.

We are ready for controllers. Create Controllers folder, and inside UserController.cs file.

We are using dependency injection in constructor of Controller. In order to be able to use this feature, we must enable it. Open Startup.cs and in ConfigureServices method add this line: services.AddScoped<UserService>().

Now let’s implement controller methods.

GetUsers() will be executed if we trigger route http://localhost:5000/api/user

GetUser() will be executed if we trigger route http://localhost:5000/api/user/{id}

CreateUser() will be executed if we trigger route http://localhost:5000/api/user (Post request)

Open terminal and run command:
dotnet build

Then command: dotnet watch run (Running this, every saved change in code will automatically reload project).

Now open postman, and let’s test our api, before adding JWT Authentication.

First we will run Post request, to add new user. Notice that id is auto assigned as string 24 chars long.

Now if we run Get request with http://localhost:5000/api/user, we should get list of users, with only one user at the moment.

And we do.

Now for the fun part, let’s add Jwt authentication.
First stop the server with ctrl + c, and add few more packages. Run next commands:

dotnet add package Microsoft.AspNetCore.Authentication

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

dotnet add package System.IdentityModel.Tokens.Jwt

Again, check .csproj file and acknowledge that these packages are there. Now in order to use Authentication of any kind, we must enable it in our project. Go to your Startup.cs file and navigate to Configure method. In it add app.UseAuthentication() method.

Now in same file we need to configure our Jwt Authentication like so:

Now the IssuerSigningKey is the secret key that we are setting, and it is used for signature validation.

Configuration.GetSection(“JwtKey”).ToString() this will get the value from appsettings.json file for given key. In my case I added JwtKey like so:

And in real world, this would be something more appropriate, or maybe you would not want to keep this key in here.

Now that we added all we need, we can write logic for authentication itself.
Open UserService, and create method Authenticate. This method will take email and password passed from login form or in our case request body, and check if credentials are valid and if so, it will create the token with data we want inside it. Method looks like this:

In here I am returning null, because FirstOrDefault will return null if it does not find match in Database. Since we are using JwtKey from our appsettings.json file, we need to assign it like so:

Just add one more assign in constructor, and you are good to go. Finally let’s use this Authenticate method in our controller, and we can test it.
So open you UserController.cs and on top add [Authorize] attribute. This will mean that you have to authorized to execute anything from this controller, in our case we are authorized by providing token.

Add new method called Login and give it [AllowAnonymous] attribute, ‘cause we do want to allow this to be executed without authorization.

We are expecting user’s credentials in request body and then we pass them to our service. If credentials are not correct we will return Unauthorized(), however when user passes authentication, we will return both user object and the token. Now you are free to return additional data if needed. Let’s test one more time.

If we try to access list of users without being authenticated:

We are getting 401 Unauthorized. Now let’s login first and get the token.

Now if we go to Jwt.io and paste our token, we will get data that we provided in, when we configured it.

Now let’s get back to user list again. Go to Authorization tab and pick Bearer Token.

Paste token inside. And send request again.

We now have our list.

Next step will be creating frontend application with React.js and connect it with this application.
Check it out 👉 here.

That is it for this tutorial, hope you find it interesting and useful. If so you can support my work and buy me a coffee 😊

Please share your thoughts, and until next time happy coding!

--

--