Something went wrong on our end
-
Abdelsamad, Mouaz R (UG - SISC) authoredAbdelsamad, Mouaz R (UG - SISC) authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
Program.cs 2.10 KiB
using Microsoft.EntityFrameworkCore;
using UserMicroservice.Models;
using UserMicroservice.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Identity;
using UserMicroservice.Handlers;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Configure your DbContext and MySQL connection here
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(builder.Configuration.GetConnectionString("DefaultConnection"),
new MariaDbServerVersion(new Version(10, 4, 20))));
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"]
};
});
// Add dependency injections
builder.Services.AddScoped<IPasswordHasher<User>, PasswordHasher<User>>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IUserService, UserService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseMiddleware<ExceptionHandler>();
app.UseHttpsRedirection();
// Middleware to check for the access token in cookies
app.Use(async (context, next) =>
{
var accessToken = context.Request.Cookies["AccessToken"];
if (!string.IsNullOrEmpty(accessToken))
{
context.Request.Headers.Append("Authorization", "Bearer " + accessToken);
}
await next();
});
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();