Identity, Authentication and Authorization .net Core v6 or later | JWT
We are going to learn:
JWT
Identity
Swagger
Open visual studio create .net core project and then install necessary packages from nuget.
Install using ui
OR using package manager console
PM> Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
Verify package installed package in dependencies
In Program.cs file add Authentication service
Also ensure to add Authentication and Authorization Middlewares
Ensure to add JWT setting in appsetting.json file
Now lets Add Identity
We can scaffold identity using visual studio or directly install necessary packages to project
It will take few seconds to scaffold the identity to project
Or Install these packages manually without scaffolding
Scaffolding automatically adds all the necessary files and update the Program.cs file
without scaffolding one has to create these files and update the Program.cs file manually.
ApplicationDbContext File
Program.cs file
Configure connection string
var connectionString = builder.Configuration.GetConnectionString("ESTOREContextConnection") ?? throw new InvalidOperationException("Connection string 'ESTOREContextConnection' not found.");
Also add connection string in appsetting.json file
"ESTOREContextConnection": "Server=MSI;Database=ESTORE;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
Install sql server and sql server management studio to access databases , if you don’t have this.
Open SSMS after install and connect with local database
Open Package Manager Console and Run migration so it will migrate identity related db and tables on database
ensure to run these both cmds
lets verify it on db
So everything is done now create AuthController to create signup and login method
Create API controller , if you created empty controller ensure these attributes available on controller
[ApiController]
[Route("[controller]")]
public class AuthController : Controller
As shown in above image add necessary dependencies , like UserManger ,SignInManger, RoleManger and Configuration;
Store: its for in-memory data save, i.e if to test add user in locally without database , but we already added identity so we will use db
GenerateJwtToken Method
Lets Add Login Request and Response model for login Method
After adding models we have to update the login method
We are using ActionResult instead of IActionResult, Because it supports generic and we can add our response model in it which will be shown in Swagger as well.
Use FromBody Attribute(Annotation) to get the userLogin parameter.
Create LoginResponse and Return it using Ok Method.
We are saving our models in Models Folder
Our UserLogin Model class with validation.
LoginResponse Model
Success Response
Error Response
Create Signup Method
Lets modify the signup method with SignupRequest model
We updated the Signup Method and added SignupRequest Model
SignupRequest Model
Test with Swagger
Send Unmatched password
Invalid Email
Now lets send valid data
Now let's test this integration by creating an authorize path with authorize attribute.
To get JWT payload i.e user id which is saved in claims, We can get it from User property which is available in Controller base class.
Test With swagger: lets modify swagger code to get access Authorize Button
Login Response
User created on db
To do the same without VS CODE
Install .net core SKD
After install verify it with CMD console
Create project
Install packages
Install jwt packages as well
In this case you have to add few files manually like AppDbContext file and update the Program.cs shown in above steps
To web app if need to scaffold items using cmd
dotnet aspnet-codegenerator identity -dc ApplicationDbContext --files "Account.Login;Account.Register;Account.Logout;Account.Manage"
Run migration and update db
Rest will be same i.e auth controller that we discuss in 1st step i.e visual studio;
JWT
Identity
Swagger
Comments
Post a Comment