| 1 | using System.Text;
|
|---|
| 2 | using System.Text.Json.Serialization;
|
|---|
| 3 | using iknow_api.Data;
|
|---|
| 4 | using iknow_api.Repositories;
|
|---|
| 5 | using iknow_api.Services;
|
|---|
| 6 | using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|---|
| 7 | using Microsoft.EntityFrameworkCore;
|
|---|
| 8 | using Microsoft.IdentityModel.Tokens;
|
|---|
| 9 |
|
|---|
| 10 | var builder = WebApplication.CreateBuilder(args);
|
|---|
| 11 | builder.Services.AddAuthentication(options =>
|
|---|
| 12 | {
|
|---|
| 13 | options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|---|
| 14 | options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|---|
| 15 | })
|
|---|
| 16 | .AddJwtBearer(options =>
|
|---|
| 17 | {
|
|---|
| 18 | options.RequireHttpsMetadata = false; // only for development
|
|---|
| 19 | options.SaveToken = true;
|
|---|
| 20 | options.TokenValidationParameters = new TokenValidationParameters
|
|---|
| 21 | {
|
|---|
| 22 | ValidateIssuer = true,
|
|---|
| 23 | ValidIssuer = "iknow-api",
|
|---|
| 24 |
|
|---|
| 25 | ValidateAudience = true,
|
|---|
| 26 | ValidAudience = "iknow-api",
|
|---|
| 27 |
|
|---|
| 28 | ValidateLifetime = true,
|
|---|
| 29 |
|
|---|
| 30 | ValidateIssuerSigningKey = true,
|
|---|
| 31 | IssuerSigningKey = new SymmetricSecurityKey(
|
|---|
| 32 | Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
|
|---|
| 33 | };
|
|---|
| 34 | });
|
|---|
| 35 | // Add services to the container.
|
|---|
| 36 | builder.Services.AddControllers()
|
|---|
| 37 | .AddJsonOptions(options =>
|
|---|
| 38 | {
|
|---|
| 39 | options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
|
|---|
| 40 | });
|
|---|
| 41 | builder.Services.AddOpenApi();
|
|---|
| 42 |
|
|---|
| 43 | // Register DbContext
|
|---|
| 44 | builder.Services.AddDbContext<AppDbContext>(options =>
|
|---|
| 45 | options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
|
|---|
| 46 |
|
|---|
| 47 | // Register your services
|
|---|
| 48 | builder.Services.AddScoped<IAuthService, AuthService>();
|
|---|
| 49 | builder.Services.AddScoped<IUserRepository, UserRepository>(); // You'll need to add the UserRepository implementation
|
|---|
| 50 | builder.Services.AddScoped<IUserService, UserService>();
|
|---|
| 51 |
|
|---|
| 52 | builder.Services.AddAuthorization();
|
|---|
| 53 | var app = builder.Build();
|
|---|
| 54 |
|
|---|
| 55 | // Configure the HTTP request pipeline.
|
|---|
| 56 | if (app.Environment.IsDevelopment())
|
|---|
| 57 | {
|
|---|
| 58 | app.MapOpenApi();
|
|---|
| 59 | }
|
|---|
| 60 |
|
|---|
| 61 | app.UseHttpsRedirection();
|
|---|
| 62 | app.UseAuthentication(); // <-- must come BEFORE UseAuthorization
|
|---|
| 63 | app.UseAuthorization();
|
|---|
| 64 | app.MapControllers();
|
|---|
| 65 |
|
|---|
| 66 | app.Run();
|
|---|