|
| 1 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 2 | +using Microsoft.IdentityModel.Tokens; |
| 3 | +using sparkly_server.Enum; |
| 4 | +using sparkly_server.Services.Auth; |
| 5 | +using sparkly_server.Services.Users; |
| 6 | +using sparkly_server.Services.UserServices; |
| 7 | +using System.Text; |
| 8 | + |
| 9 | +namespace sparkly_server; |
| 10 | + |
| 11 | +public class Program |
| 12 | +{ |
| 13 | + public static void Main(string[] args) |
| 14 | + { |
| 15 | + |
| 16 | + var jwtKey = Environment.GetEnvironmentVariable("SPARKLY_JWT_KEY")!; |
| 17 | + var jwtIssuer = Environment.GetEnvironmentVariable("SPARKLY_JWT_ISSUER") ?? "sparkly"; |
| 18 | + var jwtAudience = Environment.GetEnvironmentVariable("SPARKLY_JWT_AUDIENCE") ?? "sparkly-api"; |
| 19 | + |
| 20 | + var builder = WebApplication.CreateBuilder(args); |
| 21 | + |
| 22 | + builder.Services.AddHttpContextAccessor(); |
| 23 | + |
| 24 | + builder.Services.AddAuthorization(options => |
| 25 | + { |
| 26 | + options.AddPolicy("AdminOnly", policy => |
| 27 | + policy.RequireRole(Roles.Admin)); |
| 28 | + }); |
| 29 | + |
| 30 | + builder.Services.AddScoped<IUserRepository, UserRepository>(); |
| 31 | + builder.Services.AddScoped<IUserService, UserService>(); |
| 32 | + builder.Services.AddScoped<IJwtProvider, JwtProvider>(); |
| 33 | + builder.Services.AddScoped<IAuthService, AuthService>(); |
| 34 | + builder.Services.AddScoped<ICurrentUser, CurrentUser>(); |
| 35 | + |
| 36 | + builder.Services.AddControllers(); |
| 37 | + // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi |
| 38 | + builder.Services.AddOpenApi(); |
| 39 | + |
| 40 | + builder.Services |
| 41 | + .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) |
| 42 | + .AddJwtBearer(options => |
| 43 | + { |
| 44 | + var key = builder.Configuration["SPARKLY_JWT_KEY"] |
| 45 | + ?? throw new Exception("JWT key missing"); |
| 46 | + |
| 47 | + options.TokenValidationParameters = new TokenValidationParameters |
| 48 | + { |
| 49 | + ValidateIssuer = false, |
| 50 | + ValidateAudience = false, |
| 51 | + ValidateLifetime = true, |
| 52 | + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), |
| 53 | + ValidateIssuerSigningKey = true, |
| 54 | + ClockSkew = TimeSpan.FromMinutes(1), |
| 55 | + }; |
| 56 | + }); |
| 57 | + |
| 58 | + var app = builder.Build(); |
| 59 | + |
| 60 | + // Configure the HTTP request pipeline. |
| 61 | + if (app.Environment.IsDevelopment()) |
| 62 | + { |
| 63 | + app.MapOpenApi(); |
| 64 | + } |
| 65 | + |
| 66 | + app.UseHttpsRedirection(); |
| 67 | + |
| 68 | + app.UseAuthentication(); |
| 69 | + app.UseAuthorization(); |
| 70 | + |
| 71 | + app.MapControllers(); |
| 72 | + |
| 73 | + app.Run(); |
| 74 | + } |
| 75 | +} |
0 commit comments