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 14 great preprocessors for developers who love to code Sometimes it seems like the rules of programming are designed to make coding a chore. Here are 14 ways preprocessors can help make software development fun again. By Peter Wayner Nov 18, 2024 10 mins Development Tools Software Development feature Designing the APIs that accidentally power businesses Well-designed APIs, even those often-neglected internal APIs, make developers more productive and businesses more agile. By Jean Yang Nov 18, 2024 6 mins APIs Software Development news Spin 3.0 supports polyglot development using Wasm components Fermyon’s open source framework for building server-side WebAssembly apps allows developers to compose apps from components created with different languages. By Paul Krill Nov 18, 2024 2 mins Microservices Serverless Computing Development Libraries and Frameworks news Go language evolving for future hardware, AI workloads The Go team is working to adapt Go to large multicore systems, the latest hardware instructions, and the needs of developers of large-scale AI systems. By Paul Krill Nov 15, 2024 3 mins Google Go Generative AI Programming Languages Resources Videos