Create a WEB API Project
To create a WEB API project in Visual Studio, you can follow the given steps step by step.
- Create New Project ⇒ Project
- Search ASP.Net web application ⇒ Click Next
- Enter application name ⇒ Select your project location
➤ Add the below Nuget packages
System.IdentityModel.Tokens.Jwt
To add NuGet package you can either use Manage NuGet Packages or you can simply use below command in Package Manager Console.
install-package System.IdentityModel.Tokens.Jwt
➤ Create the Secret Key
var symmetric_Key = Convert.FromBase64String(SecretKey);
var token_Handler = new JwtSecurityTokenHandler();
You can see that the secret key will generated using this code. This key is randomly generated that means when you run again it create different secret key for you.
"RanO/dobqmVjgHfeTrAj65XDbuBPTsOygXUzS+NvKVP06WAsYB88hysfuk/x6Tt+pq+zkkPj4JRE2kunxNrFpQ=="
➤ Create a Middleware for JWT Authentication
We need a Middleware which can generate JWT and validate it based on some provided required values. To create a Middleware we have to create some classes and some methods.
Create a Folder name JWTAuth in our application and then create given classes with some piece of code having different methods serving different purposes.
JwtAuthManager.cs
JwtAuthManager class having two methods GenerateJWTToken and GetPrincipal.
GenerateJWTToken method needs two values for username and expire_in_Minutes. The username will be used as a value to Initializes a new instance of the System.Security.Claims.Claim class with the specified claim type, and value expire_in_Minutes act as Get or Set value for the ‘expiration’ claim.
JwtAuthentication.csSystem.IdentityModel.Tokens.Jwt
To add NuGet package you can either use Manage NuGet Packages or you can simply use below command in Package Manager Console.
install-package System.IdentityModel.Tokens.Jwt
➤ Create the Secret Key
var symmetric_Key = Convert.FromBase64String(SecretKey);
var token_Handler = new JwtSecurityTokenHandler();
You can see that the secret key will generated using this code. This key is randomly generated that means when you run again it create different secret key for you.
"RanO/dobqmVjgHfeTrAj65XDbuBPTsOygXUzS+NvKVP06WAsYB88hysfuk/x6Tt+pq+zkkPj4JRE2kunxNrFpQ=="
➤ Create a Middleware for JWT Authentication
We need a Middleware which can generate JWT and validate it based on some provided required values. To create a Middleware we have to create some classes and some methods.
Create a Folder name JWTAuth in our application and then create given classes with some piece of code having different methods serving different purposes.
JwtAuthManager.cs
JwtAuthManager class having two methods GenerateJWTToken and GetPrincipal.
GenerateJWTToken method needs two values for username and expire_in_Minutes. The username will be used as a value to Initializes a new instance of the System.Security.Claims.Claim class with the specified claim type, and value expire_in_Minutes act as Get or Set value for the ‘expiration’ claim.
JwtAuthentication is used to validate when particular user again requests with the generated token. JwtAuthentication class inheriting Attribute class and IAuthenticationFilter. IAuthenticationFilter is an interface having two declared function AuthenticateAsync and ChallengeAsync.
AuthenticateAsync invokes first when sending a request with the token. Two parameter context and cancellationToken belongs to AuthenticateAsync is used to get a request from the user. context will have the authentication context and cancellationToken will have the token to monitor for cancellation requests.
ValidateToken method having two parameter token and username will validate requested token is exact same or not issued to that particular user based on username. Here comes GetPrincipal method in action, GetPrinciple read token with same and validate it with TokenValidationParameters.
AuthFailureResult.cs
While Validating token, there are chances that authentication might be failed if a request having token is not valid. AuthFailureResult class inherit IHttpActionResult Interface. You have to implement ExecuteAsync that belong to IHttpActionResult. ExecuteAsync is used to perform a task contains the System.Net.Http.HttpResponseMessage when completed.
UnauthorizedResult.cs
This is use for authorization, it pass in the header.
➤ Create WEB API Controller
You need to create two different actions one for generating a token, send back to the user and second one for validating that token and expose requested data by the user. You can have both actions in the same controller or can have two separate controllers. It all depends upon the requirement of your project.
In our case we have created two separate controllers, one for creating a token and another one for validate. Have a look at below code.
RequestTokenController.cs
JwtAuthentication – It is used to at action level to protect it. It is only available when user request with validly issued JWT Token to that particular user.
Done ! We did all requirement of JWT authentication in ASP .NET Web API. Let's test this API in Postman and see how it works.
POSTMAN
Step 1: You have to enter a few details before you post details on the server.
- Enter URL of WEB API with “/RequestToken” like “http://localhost:port/RequestToken
http://localhost:58494/api/RequestToken?username=CoreProgramm&password=cp@123
Step 2: Once you get token, again you have to follow some step to authenticate generated token.
- Enter WEB API URL with “/Values” like “http://localhost:port/api/Values”
- Enter Authorization for Key under Header and for Value, you have to enter “Bearer generated-token…” Or, Select authorization type – Bearer Token and Enter Token in Token field.
WAH ! You can see we get our result |
</> Find Source Code in Github.com/CoreProgramm/
Summary
Post a Comment