.NET Core — Adding JWT Claims To Web API — Part 2 The APIs Implementation
How to add JSON Web Token to protect your web APIs and authenticate users
About
This is part 2 of .NET Core — Adding JWT Claims To Web API Part 1 The Setup. Make sure to follow Part 1
Recap for What We Going To Build
A web API that allows users to
- Sign Up (To obtain JWT token)
- Sign In (To obtain JWT token)
- Get User Profile API (Protected by JWT authorization)
The APIs implementations
Create File named AccountController.cs or whatever you like to name it under the Controllers folder. Note for simplicy I’m not going to implement it using Services/Repository design patterns. Note you need to handle stuff like some of business rules or validation that suits your needs.
The controller will contain 3 Actions:
- SignUp Action Controller, where new users can register and obtain an profile/account into our system like email, username,password..etc
- SignIn Action Controller, where users can login and obtain a JWT Authorization claim to be used next API
- GetMyProfile Action Controller, where this API will require users to be logged-in and pass JWT Authroizating token in order to fetch their Profile like email or username …etc
Controllers Setup
We will inject 3 objects in AccountController constructor by .NET core dependency injection system.
- AppDbContext the objects that allows us to communicate with our Database and manage it through Entity Framework ORM system.
- JWTBearerTokenSettings the objects that carries our JWT options from appsettings.json like
- UserManager which allows access to ASPNetCore User Identity to manage Users data and configurations
Now that construction for AccountController is completed we going to add our actions
SignUp API
This is SignUp web service that allows “anonymous users” to register into our web API and store his information into our database. First we going to create a ViewModel Folder and add a class we named it SignUpData.cs for our SignUp API that wraps up user request objects containing following in order to be stored in our database.
- Username
- Password
Now that the ViewModel is added, we can add an Action Method inside our AccountController.cs . Also after the success of user registration, we will generate a JWT token based on the user registered information to provide the client a JWT claim (token), therefore we also going to add a none Controller Action method called GenerateJWTToken.
Test SignUp Web Service
I’m going to use Postman client to test our APIs. Run the app through IDE or type the following in the Terminal
dotnet run
And do a Post request passing SignUpData, you should receive the JWT token
SignIn API
The SignIn web service will allow already registered users to SignIn by login with Email & password and then obtaining a JWT claim “token” that will allow him to access protected web-services by calling it and passing it JWT claim in the header.
Before all of that let’s add a class wrapper that accepts Sign In information for SignIn webservices as ViewModel class named SignInData.cs
Now we define SignIn Controller Action method and the a method that passed user email & password that validates it and then generating the JWT Claim if was valid credentials called ValidateUserCredentials
Test SignIn Web Service
Rerun the app through the IDE or hit Ctrl+C in the previously active Terminal to interrupt and the the following command in the Terminal
dotnet run
And do a Post request passing it Email & Password for user whom already registered user in the SignUp section. If the credentials are correct, you should receive the JWT token in the web service response.
GetMyProfile API
The last Controller action method, will be protected by an Authorization as denoted by [Authorize] tag/annotation to a middleware that expects the client/request containing a JWT token in the header (Bearer token) in order to process the request, otherwise it will return an HTTP 401Unauthorized
however if the request contains JWT claim then it will return the User information like Email, Username and his PhoneNumber in a wrapper class called UserProfile.
Create UserProfile.cs under ViewModels
And add GetMyProfile Controller Action Method. Note the [Authorize] annotation above the [Route]
Test SignIn Web Service
Testing GetMyProfile API will require previously generate Token by using the SignIn (or SignUp) web services in the request header as Bearer token. If the tokens were not expires it will
that’s all for this tutorial.
Source
You can find the complete source code on github here.