- 1// Nuget packages
- 2
- 3// Entity-> Microsoft.EntityFrameworkCore
- 4// Code first ->Microsoft.EntityFrameworkCore.Tools.
- 5// Mysql ->pomelo mysql
- 6// jwt -> Microsoft.AspNetCore.Authentication.JwtBearer
- 7
- 8
- 9
- 10
- 11using LibraryManagementApi.AuthService;
- 12using LibraryManagementApi.DBContexts;
- 13using LibraryManagementApi.Interface;
- 14using LibraryManagementApi.Repository;
- 15using Microsoft.AspNetCore.Authentication.JwtBearer;
- 16using Microsoft.IdentityModel.Tokens;
- 17using System.Text;
- 18
- 19var builder = WebApplication.CreateBuilder(args);
- 20builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
- 21
- 22// Add services to the container.
- 23
- 24builder.Services.AddControllers();
- 25// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
- 26builder.Services.AddEndpointsApiExplorer();
- 27builder.Services.AddSwaggerGen();
- 28builder.Services.AddDbContext<DBContext>();
- 29builder.Services.AddScoped<BooksInterface, BooksRepository>();
- 30builder.Services.AddScoped<UserInterface, UserRepository>();
- 31builder.Services.AddScoped<JWTHandler>();
- 32builder.Services.AddCors(options =>
- 33{
- 34 options.AddPolicy("AllowAll", policy =>
- 35 policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
- 36
- 37});
- 38
- 39
- 40builder.Services.AddAuthentication(options =>
- 41{
- 42 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
- 43 options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
- 44})
- 45.AddJwtBearer(options =>
- 46{
- 47 options.TokenValidationParameters = new TokenValidationParameters
- 48 {
- 49 ValidateIssuer = true,
- 50 ValidateAudience = true,
- 51 ValidateLifetime = true,
- 52 ValidateIssuerSigningKey = true,
- 53 ValidIssuer = builder.Configuration["Jwt:Issuer"],
- 54 ValidAudience = builder.Configuration["Jwt:Issuer"],
- 55 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
- 56 };
- 57});
- 58var app = builder.Build();
- 59
- 60// Configure the HTTP request pipeline.
- 61if (app.Environment.IsDevelopment())
- 62{
- 63 app.UseSwagger();
- 64 app.UseSwaggerUI();
- 65}
- 66
- 67app.UseHttpsRedirection();
- 68
- 69app.UseCors("AllowAll");
- 70app.UseAuthorization();
- 71app.UseAuthentication();
- 72app.MapControllers();
- 73
- 74app.Run();
Raw Paste