Take advantage of JSON Web Tokens to implement a loosely coupled security model in your ASP.Net Core applications Credit: Thinkstock ASP.Net Core is an open source, cross-platform, lean, and modular framework for building high-performance web applications. Unlike earlier versions of the framework, ASP.Net Core 2 provides support for JSON Web Tokens. In this article, we’ll draw on ASP.Net Core 2.x to see how JWT tokens can be used in a typical ASP.Net Core web application. What are JWT tokens? JSON Web Tokens (or JWTs for short) are very popular in the web development community these days. JWT is an open standard in which the sender and receiver can communicate via JSON in a secure manner. JWT tokens are typically used for authenticating and authorizing users. JWT tokens are comprised of three parts: Header —provides metadata about the type of data and the algorithm used to encrypt the data being transferred Payload—the actual data represented in JSON format Signature—used to validate the integrity of the data being transferred Create a new ASP.Net Core project First let’s create an ASP.Net Core project in Visual Studio. Assuming that .Net Core is installed in your system, follow these steps to create an ASP.Net Core application in Visual Studio 2017. In the Visual Studio IDE, click on File > New > Project. Select “ASP.Net Core Web Application (.Net Core)” from the list of templates displayed. Specify a name for the project. Click OK to save. In the “New .Net Core Web Application…” window, select “Web API.” Ensure that “Enable Docker Support” is unchecked. Select “No Authentication” as we won’t be using authentication in this example. Click OK. When you click OK, a new ASP.Net Core project will be created containing an example Controller to build and execute RESTful HTTP services. The default controller will be named ValuesController. Install JWT bearer authentication middleware If you want to authenticate users using JWT, you will need to install the following package via the NuGet Package Manager UI in Visual Studio. Microsoft.AspNetCore.Authentication.JwtBearer Alternatively, you can type in the following command in the NuGet Package Manager Console. > Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 2.0.0 You can implement basic authentication with JWT in ASP.Net Core fairly easily—it is simple. After you install the necessary middleware package, i.e. Microsoft.AspNetCore.Authentication.JwtBearer, just follow the steps outlined below. Add the JWT bearer to your ConfigureServices method Now for the code. The first step is to make a call to the AddAuthentication extension method in the ConfigureServices method of the Startup class as shown in the code snippet below. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication().AddJwtBearer(options => { options.Audience ="http://localhost:34924/"; options.Authority ="http://localhost:34925/"; }); services.AddMvc(); } Note that the ConfigureServices method is the method used to add services to the services container, making them available in your application via dependency injection. ConfigureServices will be called automatically by the runtime whenever the API is in executed. Specify the token validation parameters for AddAuthentication The next thing you should do is update the ConfigureServices method and specify the necessary validation parameters for the AddAuthentication method. Here is a quick rundown of the parameters of the AddAuthentication method and what they are used for. Audience—used to specify the intended recipient of the incoming token Authority—represents the address of the token issuing authority, i.e., the authentication server AutomaticAuthenticate—used to specify if the user defined by the token should be logged in automatically RequireHttpsMetadata—used to specify if the JWT token should be transferred only over HTTPS (note we aren’t using HTTPS in our example) The following code listing illustrates the updated ConfigureServices method. Note how the TokenValidationParameters have been used. public void ConfigureServices(IServiceCollection services) { services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration[“Jwt:Issuer”], ValidAudience = Configuration[“Jwt:Issuer”], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration[“Jwt:Key”])) }; }); services.AddMvc(); } Configure the JWT authentication service Next you can configure JWT-based authentication service in the appsettings.json file as shown in the code snippet below. ”Jwt”: { “Key”: “IDGSecretKey”, “Issuer”: “http://localhost:34924/“ } Implement JWT authentication in your ASP.Net Core app Lastly, you should make a call to the UseAuthentication method in the Configure method as shown in the code listing below. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseAuthentication(); app.UseMvc(); } This was an introductory article on how we can leverage JWT bearer token authentication in ASP.Net Core. I will discuss JWTs in more detail—including how to generate JWT tokens and how to encrypt the data—in future articles here. Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos