Hi @Ishika Garg
Your code still works well on my side, please refer to the following steps to create a new application to test it.
1.Create a New Asp.net 7 API application: named "JWTAuth“.
2.Install the "Microsoft.AspNetCore.Authentication.JwtBearer" 7.0.5 version package via NuGet.
3.Add the LoginDTO.cs class in the Models folder:
using System.ComponentModel.DataAnnotations;
namespace JWTAuth.Models
{
public class LoginDTO
{
[Required]
[StringLength(20)]
public string UserName { get; set; }
[StringLength(10)]
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
[RegularExpression(@"^((?=.*@)(?=.*[a-z])(?=.*[A-Z])(?=.*\d)).+$", ErrorMessage = "Password should contain atleast 1 capital letter,atleast 1 small letter and special character @")]
public string Password { get; set; }
}
}
4.Add the UserController API controller:
using JWTAuth.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
namespace JWTAuth.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly IConfiguration _configuration; //private readonly IUnitOfWork _unitOfWork;
public UserController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet]
[Route("get")]
[Authorize]
public string Get()
{
return "jwt is authorized";
}
[HttpPost]
[Route("login")]
public IActionResult Login([FromBody] LoginDTO login)
{
try
{
if (login.Password == "Ishika@12" && login.UserName == "Ishika@123")
{
string token = GenerateToken(login.UserName, login.Password);
var message = Ok(new { tokenstring = token });
return message;
}
else
{
var message = Unauthorized("User is not present");
return message;
}
}
catch (Exception ex)
{
var message = Problem(ex.Message);
return message;
}
}
private string GenerateToken(string userName, string password)
{
SecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtConfiguration:TokenSecret"]));
SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var token = new JwtSecurityToken(null, null,
null,
expires: DateTime.Now.AddMinutes(180),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}
5.Add the appsettings.json file as below:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"JwtConfiguration": {
//"TokenExpirationTimeInMinutes": 180,
"TokenSecret": "ASDFGHJKLqtfaaftfztfzljkjmkjhugyftyftdxrfxxthdtryjtrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrcccccccccccdxdd"
//"Issuer": "https://localhost:7194;https://localhost:7193",
//"Audience": "https://localhost:7080;https://localhost:7081",
},
"AllowedHosts": "*"
}
6.Configure the JWT service in the Program.cs file:
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o => {
o.TokenValidationParameters = new TokenValidationParameters()
{
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidateIssuer = false,
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["JwtConfiguration:TokenSecret"])),
};
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
7.Add the [Authorize]
attribute on the WeatherForecast API Controller:
The project file (JWTAuth.csproj, double click the project name, you will see it) as below:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.5" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
</Project>
Then, when using Postman to access the API controller, the result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion