Ignore:
Timestamp:
10/26/25 20:52:35 (11 months ago)
Author:
stefansaveski <stefansaveski19@…>
Branches:
master
Children:
28759eb, 4e061d8, 4f5d8fd
Parents:
8e32210
Message:

Add JWT authentication and refactor namespaces

Introduced JWT-based authentication and authorization:

  • Configured JWT authentication in Program.cs with token validation.
  • Added [Authorize] attribute to a new getstring endpoint.

Refactored namespaces for consistency:

  • Updated namespaces from iknow_api.Core.* to iknow_api.*.

Enhanced middleware and dependency injection:

  • Registered IAuthService and IUserRepository.
  • Added app.UseAuthentication() and app.UseAuthorization().

Removed unused code and dependencies:

  • Deleted WeatherForecast class.
  • Cleaned up redundant imports.

Updated project dependencies to include JWT authentication library.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • iknow-api/Program.cs

    r8e32210 r5eb7847  
     1using System.Text;
     2using iknow_api.Data;
     3using iknow_api.Repositories;
     4using iknow_api.Services;
     5using Microsoft.AspNetCore.Authentication.JwtBearer;
    16using Microsoft.EntityFrameworkCore;
    2 using iknow_api.Core.Data;
    3 using iknow_api.Services;
    4 using iknow_api.Repositories;
     7using Microsoft.IdentityModel.Tokens;
    58
    69var builder = WebApplication.CreateBuilder(args);
     10builder.Services.AddAuthentication(options =>
     11{
     12    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     13    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
     14})
     15.AddJwtBearer(options =>
     16{
     17    options.RequireHttpsMetadata = false; // only for development
     18    options.SaveToken = true;
     19    options.TokenValidationParameters = new TokenValidationParameters
     20    {
     21        ValidateIssuer = true,
     22        ValidIssuer = "iknow-api",
    723
     24        ValidateAudience = true,
     25        ValidAudience = "iknow-api",
     26
     27        ValidateLifetime = true,
     28
     29        ValidateIssuerSigningKey = true,
     30        IssuerSigningKey = new SymmetricSecurityKey(
     31            Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
     32    };
     33});
    834// Add services to the container.
    935builder.Services.AddControllers();
     
    1743builder.Services.AddScoped<IAuthService, AuthService>();
    1844builder.Services.AddScoped<IUserRepository, UserRepository>(); // You'll need to add the UserRepository implementation
    19 
     45builder.Services.AddAuthorization();
    2046var app = builder.Build();
    2147
     
    2753
    2854app.UseHttpsRedirection();
     55app.UseAuthentication(); // <-- must come BEFORE UseAuthorization
    2956app.UseAuthorization();
    3057app.MapControllers();
Note: See TracChangeset for help on using the changeset viewer.