A set of technologies in the .NET Framework for building web applications and XML web services.
Please try the followings. If you could complete (1) through (7) I will add the description and code to generate the JWT required for authentication, send the JWT to the API and obtain the JSON response
(1) Create project
Use template of Visual Studio 2022. Select the ASP.NET Core Web API:
Set the Authentication type to none:
(2) Install NuGet package
Install the Microsoft.AspNetCore.Authentication.JwtBearer:
(3) Register JWT Authntocation
Open the Program.cs and add the service and middleware for the JWT-based authentication, as follows:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace WebApiJwtCors
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Add service for JWT-based authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
};
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// Add middleware for JWT-based authentication
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
(4) Add Key and Issuer
Add Jwt element to the appsettings.json so that the TokenValidationParameters constractor in the above (3) code can obtain the values of Key and Issuer:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Jwt": {
"Key": "veryVerySecretKeyWhichMustBeLongerThan32",
"Issuer": "https://localhost:44344"
}
}
(5) Add CORS, only if required
Open the Program.cs and add the service and middleware for the CORS as follows:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace WebApiJwtCors
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Add service for CORS
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// Add service for JWT-based authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
};
});
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// Add middleware for CORS
app.UseCors(MyAllowSpecificOrigins);
// Add middleware for JWT-based authentication
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
(6) Build and confirm
Confirm that the WeatherForecast controller returns the JSON response as expected:
(7) Add [Authorize] attribute
Add [Authorize] attribute to the Get() method of WeatherForecastController as shown below:
Confirm that the WeatherForecast controller returns HTTP 401 Unauthorized response: