Parking_space_WEBAPI/WebApi_data_value/Program.cs

152 lines
4.5 KiB
C#

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Configuration;
using System.Reflection;
using System.Text;
using WebApi_data_value.Authorization;
using WebApi_data_value.Helpers;
using WebApi_data_value.Services;
var builder = WebApplication.CreateBuilder(args);
//在 ASP.NET Core 中啟用 CORS (跨原始來源要求)
builder.Services.AddCors();
// Add services to the container.
builder.Services.AddControllers();
// 連線PostgreSQL資料庫
//var connectionString = "Server=140.125.20.183;UserID=postgres;password=EL404el404;Database=postgres;port=5432;Search Path=public;CommandTimeout=1800";
var connectionString = "Server=127.0.0.1;UserID=postgres;password=EL404el404;Database=postgres;port=5432;Search Path=public;CommandTimeout=1800";
builder.Services.AddDbContext<SqlContext>(opt => opt.UseNpgsql(connectionString));
//連線MySQL資料庫
/*
builder.Services.AddDbContext<SqlContext>(opt =>
{
string connectionString = builder.Configuration.GetConnectionString("tarefasConnection");
var serverVersion = ServerVersion.AutoDetect(connectionString);
opt.UseMySql(connectionString, serverVersion);
});*/
//身分驗證
//add services to DI container
{
var services = builder.Services;
services.AddCors();
services.AddControllers();
// configure strongly typed settings object
services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
// 配置JWT身份验证
var jwtSettings = builder.Configuration.GetSection("AppSettings").Get<AppSettings>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
//ValidIssuer = "your_issuer",
// ValidAudience = "your_audience",
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secret))
};
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi_data_value", Version = "v1" });
// Configure Swagger to use JWT authentication
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
// 将JWT令牌作为所有端点的要求添加到Swagger文档
//ˇc.OperationFilter<SecurityRequirementsOperationFilter>();
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
// configure DI for application services
services.AddScoped<IJwtUtils, JwtUtils>();
services.AddScoped<IUserService, UserService>();
// 注册 HttpClient 服务
services.AddHttpClient();
}
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//註解
builder.Services.AddSwaggerGen(options =>
{
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
// app.UseSwagger();
// app.UseSwaggerUI();
//}
app.UseSwagger();
app.UseSwaggerUI();
//在 ASP.NET Core 中啟用 CORS (跨原始來源要求)
// Shows UseCors with CorsPolicyBuilder.
app.UseCors(builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.MapControllers();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();