I want how to generate jwt token
This is my Controller
public class LoginController : Controller
{
private readonly JwtContext _context;
public LoginController(JwtContext context)
{
_context = context;
}
[Route("api/Register")]
[HttpPost]
public IActionResult Post([FromBody]Register register)
{
if (ModelState.IsValid)
{
_context.Add(register);
_context.SaveChanges();
}
Console.WriteLine(register);
var ttt = _context.Registers.ToList();
return Ok(new { result = ttt });
}
}
This is my Login model where i use to stored information of login
public class Login
{
public int LoginId { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
This is my Register model where i use to stored information of Register
public class Register
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
CodePudding user response:
Below is a demo , you can refer to it.
In Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<IUsersDb>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("IUsersDb")));
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("V1", new OpenApiInfo
{
Version = "V1",
Title = "Educal API",
Description = "Main API Documantation of Educal API"
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = @"Please provide authorization token to access restricted features.",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new List<string>()
}
});
});
// ADD JWT Authentication
builder.Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.RequireHttpsMetadata = false;
o.Events = new JwtBearerEvents();
o.Events.OnTokenValidated = context =>
{
context.Response.StatusCode = 200;
return Task.CompletedTask;
};
o.Events.OnAuthenticationFailed = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
o.Events.OnChallenge = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
o.Events.OnMessageReceived = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
var key = Encoding.UTF8.GetBytes(builder.Configuration["JWT:Key"]);
o.SaveToken = true;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["JWT:Issuer"],
ClockSkew = TimeSpan.Zero,
//ValidAudience = builder.Configuration["JWT:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
builder.Services.AddAuthorization(auth =>
{
auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser().Build());
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options => {
options.SwaggerEndpoint("/swagger/V1/swagger.json", "Main API Documantation of Educal API");
});
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
IAuthenticationService:
public interface IAuthenticationService
{
Models.AuthenticationToken? Authenticate(User user);
}
AuthenticationService:
public class AuthenticationService : IAuthenticationService
{
private readonly IConfiguration _configuration;
private readonly IUsersDb _usersDb;
public AuthenticationService(IConfiguration configuration, IUsersDb usersDb)
{
_configuration = configuration;
_usersDb = usersDb;
}
public Models.AuthenticationToken? Authenticate(User user)
{
var foundUser = _usersDb.User
.FirstOrDefault(x => x.Name == user.Name && x.Password == user.Password);
if (foundUser == null)
{
return null;
}
//If user found then generate JWT
return CreateAuthenticationToken(foundUser);
}
private Models.AuthenticationToken CreateAuthenticationToken(User user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var tokenKey = Encoding.UTF8.GetBytes(_configuration["JWT:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new(ClaimTypes.Name, user.Name),
}),
Expires = DateTime.UtcNow.AddMinutes(10),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey),
SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return new Models.AuthenticationToken()
{
Token = tokenHandler.WriteToken(token),
};
}
}
AuthenticationToken:
public class AuthenticationToken
{
public string Token { get; set; }
}
UsersController:
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IAuthenticationService _authenticationService;
private readonly IUsersDb _usersDb;
public UsersController(IAuthenticationService authenticationService, IUsersDb usersDb)
{
_authenticationService = authenticationService;
_usersDb = usersDb;
}
[AllowAnonymous]
[HttpPost]
[Route("authenticate")]
public IActionResult Authenticate(User user)
{
var token = _authenticationService.Authenticate(user);
if (token == null)
{
return Unauthorized();
}
return Ok(token);
}
}
User
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
}
IUsersDb:
public class IUsersDb : DbContext
{
public IUsersDb(DbContextOptions<IUsersDb> options)
: base(options)
{
}
public DbSet<User> User { get; set; }
}
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"IUsersDb": "Server=(localdb)\\mssqllocaldb;Database=IUsersDb-7dc5b790-765f-4381-988c-5167405bb107;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"JWT": {
"Key": "fc746b61cde4f6665d3f9791446cd5395661860c0075a905ed9810b7391af467",
"Issuer": "Comply",
"Audience": "comply"
}
}
Result: