Dylan  Iqbal

Dylan Iqbal


JWT Authentication with ASP.NET WEB API

You can also read another article ( How to secure ASP.NET WEB API using Token Based Authentication) based on Token based authentication on Code-Adda to have some idea about how token based authentication works.

Create a WEB API Project

To create a WEB API project in Visual Studio, you can follow the given steps step by step.

  1. Open Visual Studio
  2. Go to the file menu
  3. Create > Project
  4. Select Web
  5. Select “asp.net web application”
  6. Enter application name
  7. Select your project location
  8. Click on add button

It will bring up a new dialog window for select template > here I will select empty template > and then checked MVC & Web API checkbox from Add folder and core references for > and then click on Ok button.

Add NuGet package :


To add NuGet package you can either use Manage NuGet Packages windows after right click on References available in Solution Explorer or you can simply use below command in Package Manager Console.

install-package System.IdentityModel.Tokens.Jwt

Create a Middleware for JWT Authentication

You need a middleware which can generate JWT and validate it based on some provided required values. To create a middleware you have to create some classes and some methods. Let’s see one by one.

Create a Folder name Auth in your application and then create given classes with some piece of code having different methods serving different purposes.

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.

You can use HMACSHA256 to create your own SecretKey. It belongs to System.Security.Cryptography namespace. Use below code to generate your own secret code

var hmac = new HMACSHA256(); var key = Convert.ToBase64String(hmac.Key);

As of now, you might be thinking I’ve not written any single word for the second method which is GetPrinciple of JwtAuthManager class. Don’t worry, we’ll go through with this later because to generate token only GenerateJWTToken method will work.

When user request with the valid required credential to get JSON Web Token, GenerateJWTToken comes in action and create a token for that particular user. Have a look at below image where you can see what different things combined in order to create a token.

Fine! I hope till now you have created Token successfully with the help of above code, now next thing is to validate it when that particular user again requests with the generated token. We use below code to validate the token. Have a look.

JwtAuthentication class inheriting Attribute class and IAuthenticationFilter. IAuthenticationFilter is an interface having two declared function AuthenticateAsync and ChallengeAsync.

Note :

Attribute class represent a base class with a custom attribute. IAuthenticationFilter Interface Define a filter that performs authentication.

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.

While Validating token, there are chances that authentication might be failed if a request having token is not valid. You can deal with same as given below code

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.

you can use below code to add authorization 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. For Demo purpose, I have created two separate controllers, one for creating a token and another one for validate. Have a look at below code.

RequestTokenController – To create a JWT and issue to those user whoever request with valid credentials.

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.

Great. Now you have created your WEB API with JWT based authentication. You can use WEB API testing tools like Fiddler or Postman. Don’t worry we will guide you how to check. Here we are going to learn how to consume WEB API using postman. Follow given steps

Step 1: You have to enter a few details before you post details on the server.

Step 2: Once you get token, again you have to follow some step to authenticate generated token.

  • Select Type – GET
  • Enter WEB API URL with “/Values” in Params 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.
  • Click on the Send button

Once you click on the send button after entering all required field. you can see the output. If there is 200 Ok. Status which means you have successfully authenticated JSON Web Token and get back the result. In case if you have not provided valid token you will get an unauthorized error.

You can download complete source code from here – Download Source Code

#asp.net #api #java

What is GEEK

Buddha Community

Einar  Hintz

Einar Hintz


jQuery Ajax CRUD in ASP.NET Core MVC with Modal Popup

In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.

To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.

Sub-topics discussed :

  • Form design for insert and update operation.
  • Display forms in modal popup dialog.
  • Form post using jQuery Ajax.
  • Implement MVC CRUD operations with jQuery Ajax.
  • Loading spinner in .NET Core MVC.
  • Prevent direct access to MVC action method.

Create ASP.NET Core MVC Project

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).

From new project window, Select Asp.Net Core Web Application_._

Image showing how to create ASP.NET Core Web API project in Visual Studio.

Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.

Showing project template selection for .NET Core MVC.

Setup a Database

Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.

Showing list of NuGet Packages for Entity Framework Core

Now let’s define DB model class file – /Models/TransactionModel.cs.

public class TransactionModel
    public int TransactionId { get; set; }

    [Column(TypeName ="nvarchar(12)")]
    [DisplayName("Account Number")]
    [Required(ErrorMessage ="This Field is required.")]
    [MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
    public string AccountNumber { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Beneficiary Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BeneficiaryName { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Bank Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BankName { get; set; }

    [Column(TypeName ="nvarchar(11)")]
    [DisplayName("SWIFT Code")]
    [Required(ErrorMessage = "This Field is required.")]
    public string SWIFTCode { get; set; }

    [Required(ErrorMessage = "This Field is required.")]
    public int Amount { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime Date { get; set; }


Here we’ve defined model properties for the transaction with proper validation. Now let’s define  DbContextclass for EF Core.

#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup

Create Asp Net Web API for CRUD operation | CRUD Using Asp Net Api

#api #api 2 #restful api #asp.net api #asp.net core api

ASP.Net Web development Company USA | WebClues Infotech

A versatile Web & Mobile App Development framework technology that is fast, reliable, and easy to use is ASP.NET. ASP.NET gives the developer complete control over development and can be used on any project big or small.

Want to develop a website or mobile app with ASP.NET?

WebClues Infotech with years of experience and a highly skilled development team can be your go-to agency for your Web & Mobile App Development requirements. With an expert developer team of more than 150+ members, WebClues Infotech has successfully delivered more than 1500 projects worldwide.

Want to know more about the ASP.NET framework?

Visit: https://www.webcluesinfotech.com/asp-net-web-development/

Share your requirements https://www.webcluesinfotech.com/contact-us/

View Portfolio https://www.webcluesinfotech.com/portfolio/

#asp.net web development company #asp.net web development company usa #asp.net development company in india #asp.net development company #.net software development company #hire asp.net developer

Hire ASP.Net Developers

Looking to outsource your asp dot net development requirement?

ASP.Net is a special feature of the DOT Net framework created by Microsoft. At HourlyDeveloper.io, we have a team of experienced ASP.Net developers who are experts in delivering custom solutions based on your business requirements. Hire ASP.Net Developers who will provide tailored solutions to facilitate your business growth.

Consult with experts: https://bit.ly/3fNpVqr

#hire asp.net developers #asp.net development company #asp.net development services #asp.net development #asp.net developer #asp.net