Configure the JWT Authentication for the Web API | XAF: Cross-Platform .NET App UI & Web API (2024)

  • 5 minutes to read

Enable Authentication in a New Project

Use the Solution Wizard to create a Web API project with the JWT authentication. If you choose Standard authentication on the Choose Security page, the wizard generates JWT authentication scaffolding code.

Configure the JWT Authentication for the Web API | XAF: Cross-Platform .NET App UI & Web API (1)

You can replace the autogenerated IssuerSigningKey value with your JWT signing key and change other JWT settings in the appsettings.json file. We recommend that you use the Secret Manager tool to store the signing key. You can store it in the appsettings.json file for testing purposes only.

File: MySolution.WebApi\appsettings.json (MySolution.Blazor.Server\appsettings.json)

  • JSON
// ..."Authentication": { "Jwt": { "Issuer": "My", "Audience": "http://localhost:4200", "IssuerSigningKey": "c1d2e0a7-405b-40be-9b36-fa93469b673a" }} // ...

See the following section for information on how to test the JWT authentication: Use the Swagger UI to Test the JWT Authentication.

Enable Authentication in an Existing Project

To add the JWT authentication to an existing Web API or Blazor Server project, follow the steps below.

Step 1. Install the Required NuGet Packages

Install the following NuGet packages to the MySolution.WebApi (MySolution.Blazor.Server) and MySolution.Module projects:

  • DevExpress.ExpressApp.Security.AspNetCore
  • Microsoft.AspNetCore.Authentication.JwtBearer
  • DevExpress.ExpressApp.Security.Xpo - in XPO applications
  • DevExpress.EntityFrameworkCore.Security - in EF Core applications

See the following topic for details: Choose Between Offline and Online DevExpress NuGet Feeds.

Step 2. Modify appsettings.json

Add the Jwt option to the Authentication section in the appsettings.json file.

File: MySolution.WebApi\appsettings.json (MySolution.Blazor.Server\appsettings.json)

  • JSON
// ..."Authentication": { "Jwt": { "Issuer": "My", "Audience": "http://localhost:4200", "IssuerSigningKey": "c1d2e0a7-405b-40be-9b36-fa93469b673a" }}, // ...

The IssuerSigningKey value is an autogenerated key. You can replace it with your JWT signing key. You can store it in the appsettings.json file for testing purposes only. We recommend that you use the Secret Manager tool to store the signing key.

Step 3. Modify Startup.cs

Add the following code to the ConfigureServices method to enable authentication:

File: MySolution.WebApi\Startup.cs (MySolution.Blazor.Server\Startup.cs)

  • C#
using DevExpress.ExpressApp.Security;using DevExpress.Persistent.BaseImpl.PermissionPolicy;using Microsoft.AspNetCore.Authorization;using Microsoft.Extensions.DependencyInjection;// ...public void ConfigureServices(IServiceCollection services) { //... services.AddXafAspNetCoreSecurity(Configuration, options => { options.RoleType = typeof(PermissionPolicyRole); options.UserType = typeof(MySolution.Module.BusinessObjects.ApplicationUser); options.UserLoginInfoType = typeof(MySolution.Module.BusinessObjects.ApplicationUserLoginInfo); // in XPO applications, uncomment the following line // options.Events.OnSecurityStrategyCreated = securityStrategy => ((SecurityStrategy)securityStrategy).RegisterXPOAdapterProviders(); options.SupportNavigationPermissionsForTypes = false; }) .AddAuthenticationStandard(options => { options.IsSupportChangePassword = true; }); var authentication = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme); // The AddJwtBearer method adds JWT credentials to the XAF authentication. authentication .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = Configuration["Authentication:Jwt:Issuer"], ValidAudience = Configuration["Authentication:Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Authentication:Jwt:IssuerSigningKey"])) }; }); services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder( JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser() .RequireXafAuthentication() .Build(); }); // ... services.AddSwaggerGen(c => { c.EnableAnnotations(); c.SwaggerDoc("v1", new OpenApiInfo { Title = "MySolution API", Version = "v1", Description = @"Use AddXafWebApi(Configuration, options) in the MySolution.WebApi\Startup.cs file to make Business Objects available in the Web API." }); // The AddSecurityDefinition and AddSecurityRequirement methods enable the JWT authentication for the Swagger UI. c.AddSecurityDefinition("JWT", new OpenApiSecurityScheme() { Type = SecuritySchemeType.Http, Name = "Bearer", Scheme = "bearer", BearerFormat = "JWT", In = ParameterLocation.Header }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme, Id = "JWT" } }, new string[0] }, }); });

Step 4. Add a JWT Authentication Service

You can implement your own JWT service, or use the JWT service that the Solution Wizard generates. You can find the auto-generated service code below. To use this JWT service, create the JWT folder in the MySolution.WebApi (MySolution.Blazor.Server) project and add the AuthenticationController.cs file to this folder.

File: MySolution.WebApi\JWT\AuthenticationController.cs (MySolution.Blazor.Server\JWT\AuthenticationController.cs)

  • C#
using System;using System.IdentityModel.Tokens.Jwt;using System.Security.Claims;using System.Text;using DevExpress.ExpressApp.Security;using DevExpress.ExpressApp.Security.Authentication;using Microsoft.AspNetCore.Mvc;using Swashbuckle.AspNetCore.Annotations;namespace MySolution.WebApi.JWT { [ApiController] [Route("api/[controller]")] public class AuthenticationController : ControllerBase { readonly IStandardAuthenticationService securityAuthenticationService; readonly IConfiguration configuration; public AuthenticationController(IStandardAuthenticationService securityAuthenticationService, IConfiguration configuration) { this.securityAuthenticationService = securityAuthenticationService; this.configuration = configuration; } [HttpPost("Authenticate")] public IActionResult Authenticate( [FromBody] [SwaggerRequestBody(@"For example: <br /> { ""userName"": ""Admin"", ""password"": """" }")] AuthenticationStandardLogonParameters logonParameters ) { ClaimsPrincipal user = securityAuthenticationService.Authenticate(logonParameters); if(user != null) { var issuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Authentication:Jwt:IssuerSigningKey"])); var token = new JwtSecurityToken( issuer: configuration["Authentication:Jwt:Issuer"], audience: configuration["Authentication:Jwt:Audience"], claims: user.Claims, expires: DateTime.Now.AddHours(2), signingCredentials: new SigningCredentials(issuerSigningKey, SecurityAlgorithms.HmacSha256) ); return Ok(new JwtSecurityTokenHandler().WriteToken(token)); } return Unauthorized("User name or password is incorrect."); } }}

Step 5. Add the ApplicationUser and ApplicationUserLoginInfo Business Objects

XAF requires the ApplicationUser and ApplicationUserLoginInfo business objects to store user information. Add these business objects to the MySolution.Module project as described in the following topic: Use the Security System.

Use the Swagger UI to Test the JWT Authentication

1.If your solution includes a Web API project, right-click the project in the Solution Explorer and choose Debug | Start new instance to run the Web API project. A browser displays the page with the available endpoints.

If your solution includes a startup Blazor Server project with the Web API, run the application. Add /swagger to the application address (for example, https://localhost:44318/swagger ) and press Enter to display a page with available endpoints.

Refer to the following link for more information on the page’s UI: Swagger UI.

  1. Expand the Post Authentication endpoint and click the Try it out button.

  2. In the displayed form, enter the userName and password for an authorized user. In a template application, use Admin as the user name and an empty string as the password.

  3. Copy the public key from the Response body, click the Authorize button Configure the JWT Authentication for the Web API | XAF: Cross-Platform .NET App UI & Web API (2) to open the Available authorizations form, and paste the public key in the Value editor to enable the JWT authentication.

Configure the JWT Authentication for the Web API | XAF: Cross-Platform .NET App UI & Web API (3)

Refer to the following topic for information on how to create Web API endpoints: Create Endpoints and Test the Web API.

See Also

User Logon and Authentication

Active Directory and OAuth2 Authentication Providers in ASP.NET Core Blazor Applications

Configure the JWT Authentication for the Web API | XAF: Cross-Platform .NET App UI & Web API (2024)

FAQs

Configure the JWT Authentication for the Web API | XAF: Cross-Platform .NET App UI & Web API? ›

To authenticate a user, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to your backend API. API Gateway validates the token on behalf of your API, so you don't have to add any code in your API to process the authentication.

How to implement JWT authentication in .NET core Web API? ›

NET Core.
  1. Step 1: Create Your New . NET Core Web API Project. ...
  2. Step 2: Install Required NuGet Packages. ...
  3. Step 3: Configure JWT Authentication in 'Startup. ...
  4. Step 4: Add the JWT Middleware to the Pipeline. ...
  5. Step 5: Generate the JWT Tokens. ...
  6. Step 6: Authenticate Users And Issue The JWT Tokens. ...
  7. Step 8: Validate And Decode JWT Tokens.
May 27, 2024

How to implement JWT in API? ›

How to Implement JWT?
  1. Generate a secret key.
  2. Create a JWT using the secret key.
  3. Send the JWT to the client.
  4. The client includes the JWT in subsequent requests.
  5. The server reads the JWT from the request header.
  6. The server Base64Url decodes the header and payload.
May 27, 2024

How to validate JWT token in .NET 5 Apis? ›

The JWT validation is based on the following five criteria:
  1. Token structure. The first check is about the token's structure. ...
  2. Token integrity. The next check is for the token's integrity. ...
  3. Token expiration. JWTs have an expiration time defined in the exp claim. ...
  4. Expected authority. ...
  5. Expected audience.
Aug 8, 2023

How to use JWT token for authentication and authorization? ›

To authenticate a user, a client application must send a JSON Web Token (JWT) in the authorization header of the HTTP request to your backend API. API Gateway validates the token on behalf of your API, so you don't have to add any code in your API to process the authentication.

How do you implement basic authentication in .NET core Web API? ›

In IIS Manager, go to Features View, select Authentication, and enable Basic authentication. In your Web API project, add the [Authorize] attribute for any controller actions that need authentication. A client authenticates itself by setting the Authorization header in the request.

Why do we use a JWT token in the Web API? ›

The main advantage of JWT tokens is that the server doesn't need to maintain session data, which can be significant for a large service. For example, to maintain authentications of many users, in a standard session workflow the server has a list of all sessions with the authenticated user data.

How to secure your .net web API with token authentication? ›

Secure a Web API with a JWT Token
  1. Create a Web API Project.
  2. Test the API.
  3. Configure Authentication and JWT.
  4. Enable HTTPS and Authentication.
  5. Add a Service.
  6. Add a Controller.
  7. Enable Authentication for the Sample Controller.
  8. Testing the Sample API.

Is JWT good for API authentication? ›

Any API that requires authentication can easily switch over to JWT's authorization. With JWT authorization, you get a user-based authentication. Once the user is authenticated, the user gets a secure token that they can use on all systems. The management of the user (and therefore the token) is centralized.

How to validate a JWT in API? ›

Here are the key steps for performing JWT validation:
  1. Retrieve and parse the JSON Web Key Set (JWKs)
  2. Decode the token.
  3. Verify the claims.
  4. Verify the signature.
Jan 22, 2024

What is required for JWT authentication? ›

Here is how JWT can be used in an authentication flow: A user provides their credentials (e.g., username and password) and sends them to the server. The server validates the credentials. If they are correct, the server generates a JWT containing the user's information (in a claim) and signs it with a secret key.

What is the difference between JWT and token authentication? ›

Choosing between JWT and server-side token authentication depends on your use case, security needs, and scalability requirements. JWT is suitable for stateless scenarios and APIs, while server-side tokens work best for session-based authentication in web applications.

How do I assign a JWT token? ›

To authenticate in the JWT Grant flow, you will need to create a JWT containing data on the authentication request, then exchange it for an access token. Note: Although this information is required to create a JWT, it is not necessarily encoded within the created JWT.

How to implement authorization in .NET Core? ›

Authorization in ASP.NET Core is controlled with the [Authorize] attribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users.

How to implement JWT token in Web API PHP? ›

Here's how it works:
  1. We create a header for the token. ...
  2. Next, we take the payload data (the information we want to include in the token) and turn that into a base64URL format too.
  3. After that, we combine the encoded header and payload with our secret key to create a signature.
Apr 24, 2024

Top Articles
Is there a difference between login & signup for social?
How to Deposit and Withdraw NGN on Binance | Binance Blog
Average Jonas Wife
Truist Bank Near Here
Enrique Espinosa Melendez Obituary
Hannaford Weekly Flyer Manchester Nh
Nco Leadership Center Of Excellence
The Definitive Great Buildings Guide - Forge Of Empires Tips
CKS is only available in the UK | NICE
Best Theia Builds (Talent | Skill Order | Pairing + Pets) In Call of Dragons - AllClash
Flat Twist Near Me
Mndot Road Closures
Craigslist Greenville Craigslist
Buying risk?
Craigslist Cars Nwi
ExploreLearning on LinkedIn: This month&#39;s featured product is our ExploreLearning Gizmos Pen Pack, the…
Arboristsite Forum Chainsaw
7543460065
Cyndaquil Gen 4 Learnset
Willam Belli's Husband
Dirt Removal in Burnet, TX ~ Instant Upfront Pricing
Illinois VIN Check and Lookup
Kayky Fifa 22 Potential
How your diet could help combat climate change in 2019 | CNN
Project, Time & Expense Tracking Software for Business
Buying Cars from Craigslist: Tips for a Safe and Smart Purchase
Yonkers Results For Tonight
Airline Reception Meaning
Anonib Oviedo
Used Patio Furniture - Craigslist
Idle Skilling Ascension
Medline Industries, LP hiring Warehouse Operator - Salt Lake City in Salt Lake City, UT | LinkedIn
Section 408 Allegiant Stadium
Plasma Donation Racine Wi
Wisconsin Volleyball Team Leaked Uncovered
Save on Games, Flamingo, Toys Games & Novelties
Consume Oakbrook Terrace Menu
Pawn Shop Open Now
Bismarck Mandan Mugshots
Miracle Shoes Ff6
Gateway Bible Passage Lookup
My Locker Ausd
Best Restaurants Minocqua
Silive Obituary
Sun Tracker Pontoon Wiring Diagram
Devon Lannigan Obituary
How Much Is 10000 Nickels
American Bully Puppies for Sale | Lancaster Puppies
Myapps Tesla Ultipro Sign In
Black Adam Showtimes Near Kerasotes Showplace 14
OSF OnCall Urgent Care treats minor illnesses and injuries
Fetllife Com
Latest Posts
Article information

Author: Tyson Zemlak

Last Updated:

Views: 5795

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Tyson Zemlak

Birthday: 1992-03-17

Address: Apt. 662 96191 Quigley Dam, Kubview, MA 42013

Phone: +441678032891

Job: Community-Services Orchestrator

Hobby: Coffee roasting, Calligraphy, Metalworking, Fashion, Vehicle restoration, Shopping, Photography

Introduction: My name is Tyson Zemlak, I am a excited, light, sparkling, super, open, fair, magnificent person who loves writing and wants to share my knowledge and understanding with you.