Files
DiunaBI/WebAPI/Program.cs

80 lines
2.3 KiB
C#
Raw Normal View History

2023-02-22 12:12:38 +01:00
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using WebAPI;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("SQLDatabase");
2023-09-18 19:41:39 +02:00
builder.Services.AddDbContext<AppDbContext>(x => {
x.UseSqlServer(connectionString);
x.EnableSensitiveDataLogging();
});
2023-02-22 12:12:38 +01:00
builder.Services.AddCors(options =>
{
options.AddPolicy("CORSPolicy", builder =>
{
builder.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
builder.WithOrigins("https://diuna.bim-it.pl")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
builder.Services.AddControllers();
2023-11-12 17:54:15 +01:00
2023-02-22 12:12:38 +01:00
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
2023-11-12 14:41:44 +01:00
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Secret"]!))
2023-02-22 12:12:38 +01:00
};
});
2023-11-12 14:41:44 +01:00
builder.Services.AddAuthentication();
2023-02-22 12:12:38 +01:00
builder.Services.AddSingleton(typeof(GoogleSheetsHelper));
builder.Services.AddSingleton(typeof(GoogleDriveHelper));
var app = builder.Build();
2023-11-12 17:54:15 +01:00
2023-02-22 12:12:38 +01:00
app.Use(async (context, next) =>
{
string token = context.Request.Headers["Authorization"].ToString();
2024-06-06 20:25:20 +02:00
if (token.Length > 0 && !context.Request.Path.ToString().Contains("getForPowerBI")) {
2023-02-22 12:12:38 +01:00
var handler = new JwtSecurityTokenHandler();
var data = handler.ReadJwtToken(token.Split(' ')[1]);
context.Request.Headers.Add("UserId", new Microsoft.Extensions.Primitives.StringValues(data.Subject));
}
await next(context);
});
app.UseCors("CORSPolicy");
2023-11-12 14:41:44 +01:00
app.UseAuthentication();
2023-02-22 12:12:38 +01:00
app.UseAuthorization();
app.MapControllers();
app.Run();