Add authentication and authorization (#21)

Reviewed-on: #21
This commit was merged in pull request #21.
This commit is contained in:
2025-04-21 01:53:58 +02:00
parent 51dab81121
commit 033747899b
55 changed files with 2186 additions and 317 deletions

View File

@@ -1,8 +1,14 @@
using GameIdeas.Resources;
using GameIdeas.Shared.Model;
using GameIdeas.WebAPI.Context;
using GameIdeas.WebAPI.Services.Categories;
using GameIdeas.WebAPI.Services.Games;
using GameIdeas.WebAPI.Services.Users;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
@@ -27,9 +33,38 @@ Action<DbContextOptionsBuilder> dbContextOptions = options =>
// Add services to the container.
services.AddDbContext<GameIdeasContext>(dbContextOptions);
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<GameIdeasContext>()
.AddDefaultTokenProviders();
var jwtKey = Environment.GetEnvironmentVariable("JWT_KEY")
?? throw new ArgumentNullException(message: "Invalid key for JWT token", null);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Environment.GetEnvironmentVariable("JWT_ISSUER"),
ValidAudience = Environment.GetEnvironmentVariable("JWT_AUDIENCE"),
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
};
});
services.AddAuthorization();
services.AddSingleton<TranslationService>();
services.AddSingleton<Translations>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IGameReadService, GameReadService>();
services.AddScoped<IGameWriteService, GameWriteService>();
services.AddScoped<ICategoryService, CategoryService>();