|
|
|
using System.Text;
|
|
|
|
using backend.Models;
|
|
|
|
using backend.Services;
|
|
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
using Microsoft.OpenApi.Models;
|
|
|
|
|
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
|
|
|
|
// Add services to the container.
|
|
|
|
|
|
|
|
builder.Services.Configure<BlogDatabaseSettings>(builder.Configuration.GetSection("BlogDatabase"));
|
|
|
|
|
|
|
|
|
|
|
|
builder.Services.AddSingleton<UserService>();
|
|
|
|
builder.Services.AddSingleton<BlogPostService>();
|
|
|
|
|
|
|
|
builder.Services.AddControllers();
|
|
|
|
|
|
|
|
//Authentication
|
|
|
|
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(
|
|
|
|
options =>
|
|
|
|
{
|
|
|
|
options.RequireHttpsMetadata = false;
|
|
|
|
options.SaveToken = false;
|
|
|
|
options.TokenValidationParameters = new TokenValidationParameters
|
|
|
|
{
|
|
|
|
ValidateIssuer = true,
|
|
|
|
ValidateAudience = true,
|
|
|
|
ValidateLifetime = true,
|
|
|
|
ValidIssuer = builder.Configuration["Jwt:Issuer"],
|
|
|
|
ValidAudience = builder.Configuration["Jwt:Audience"],
|
|
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:secret"]))
|
|
|
|
};
|
|
|
|
});
|
|
|
|
|
|
|
|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
|
|
|
builder.Services.AddEndpointsApiExplorer();
|
|
|
|
builder.Services.AddSwaggerGen(c =>
|
|
|
|
{
|
|
|
|
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebServer", Version = "v1" });
|
|
|
|
|
|
|
|
// We need to tell swagger that we want to support authentication
|
|
|
|
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
|
|
|
|
{
|
|
|
|
Name = "Authorization",
|
|
|
|
Type = SecuritySchemeType.Http,
|
|
|
|
Scheme = "Bearer",
|
|
|
|
In = ParameterLocation.Header,
|
|
|
|
BearerFormat = "Bearer",
|
|
|
|
Description = "The Bearer token needed to access the initial part of the api.",
|
|
|
|
});
|
|
|
|
|
|
|
|
// And again since once is not enough?
|
|
|
|
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
|
|
|
{
|
|
|
|
{
|
|
|
|
new OpenApiSecurityScheme
|
|
|
|
{
|
|
|
|
Reference = new OpenApiReference
|
|
|
|
{
|
|
|
|
Type = ReferenceType.SecurityScheme,
|
|
|
|
Id = "Bearer",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
Array.Empty<string>()
|
|
|
|
},
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
var app = builder.Build();
|
|
|
|
|
|
|
|
// Configure the HTTP request pipeline.
|
|
|
|
if (app.Environment.IsDevelopment())
|
|
|
|
{
|
|
|
|
app.UseStaticFiles();
|
|
|
|
app.UseSwagger();
|
|
|
|
app.UseSwaggerUI(c => c.InjectStylesheet("/swagger-ui/darkMode.css"));
|
|
|
|
}
|
|
|
|
|
|
|
|
app.UseHttpsRedirection();
|
|
|
|
|
|
|
|
app.UseAuthentication();
|
|
|
|
app.UseAuthorization();
|
|
|
|
|
|
|
|
app.MapControllers();
|
|
|
|
|
|
|
|
app.Run();
|