- 移除 `UserInfoController`,新增 `UserControllers` 使用 `UserService` - 添加 `UserService` 用于处理用户信息 - 新增 `UserProfile` DTO - 添加数据库迁移以支持用户表结构
155 lines
4.7 KiB
C#
155 lines
4.7 KiB
C#
using System.Reflection;
|
||
using System.Text;
|
||
using AGSS.DbSet;
|
||
using AGSS.Models;
|
||
using AGSS.Models.Entities;
|
||
using AGSS.Models.Template;
|
||
using AGSS.Utilities;
|
||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||
using Microsoft.AspNetCore.Identity;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Microsoft.IdentityModel.Tokens;
|
||
using Microsoft.OpenApi.Models;
|
||
|
||
var builder = WebApplication.CreateBuilder(args);
|
||
|
||
var configuration=builder.Configuration;
|
||
var domain = builder.Configuration["Auth0:Domain"];
|
||
var audience = builder.Configuration["Auth0:Audience"];
|
||
|
||
builder.Services.AddCors(options =>
|
||
{
|
||
options.AddPolicy("AllowAll", builder =>
|
||
{
|
||
builder.AllowAnyOrigin() // 允许所有来源
|
||
.AllowAnyHeader()
|
||
.AllowAnyMethod();
|
||
});
|
||
});
|
||
|
||
|
||
// 数据库配置(PGSQL)
|
||
builder.Services.AddDbContext<ApplicationDbContext>(opt =>
|
||
opt.UseNpgsql(builder.Configuration.GetConnectionString("DBContext")));
|
||
|
||
// Identity 配置
|
||
builder.Services.AddIdentity<UserModel, IdentityRole>()
|
||
.AddEntityFrameworkStores<ApplicationDbContext>()
|
||
.AddDefaultTokenProviders()
|
||
.AddDefaultUI();
|
||
|
||
// 注册 UserService
|
||
builder.Services.AddScoped<UserService>();
|
||
|
||
builder.Services.AddScoped<Jwt>();
|
||
|
||
builder.Services.AddAuthentication(options =>
|
||
{
|
||
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
|
||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||
})
|
||
.AddJwtBearer(options =>
|
||
{
|
||
options.TokenValidationParameters = new TokenValidationParameters
|
||
{
|
||
ValidateIssuer = true,
|
||
ValidateAudience = true,
|
||
ValidateLifetime = true,
|
||
ValidateIssuerSigningKey = true,
|
||
ValidIssuer = builder.Configuration["Jwt:Issuer"],
|
||
ValidAudience = builder.Configuration["Jwt:Audience"],
|
||
IssuerSigningKey = new SymmetricSecurityKey(
|
||
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
|
||
};
|
||
options.Events = new JwtBearerEvents
|
||
{
|
||
OnChallenge = context =>
|
||
{
|
||
context.HandleResponse();
|
||
context.Response.StatusCode = 200;
|
||
context.Response.ContentType = "application/json";
|
||
return context.Response.WriteAsJsonAsync(new ReturnTemplate(401, "你提供了一个错误的Token,所以我们无法验证你的身份,唔......", null));
|
||
}
|
||
};
|
||
}).AddMicrosoftAccount(microsoftOptions =>
|
||
{
|
||
microsoftOptions.ClientId = configuration["Authentication:Microsoft:ClientId"];
|
||
microsoftOptions.ClientSecret = configuration["Authentication:Microsoft:ClientSecret"];
|
||
});
|
||
|
||
|
||
|
||
builder.Services.AddAuthorization();
|
||
|
||
builder.Services.AddControllers();
|
||
// 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 = "ZeroNode后端文档", Version = "1.0.0", Description = "使用了Dotnet9.0,数据库采用PGSql,作者:罗澜,7000" });
|
||
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
|
||
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
|
||
c.IncludeXmlComments(xmlPath);
|
||
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||
{
|
||
In = ParameterLocation.Header,
|
||
Type = SecuritySchemeType.ApiKey,
|
||
Description = "直接在下框中输入Bearer {token}(注意两者之间是一个空格)",
|
||
Name = "Authorization",
|
||
BearerFormat = "JWT",
|
||
Scheme = "Bearer"
|
||
});
|
||
c.AddSecurityRequirement(new OpenApiSecurityRequirement
|
||
{
|
||
{
|
||
new OpenApiSecurityScheme
|
||
{
|
||
Reference = new OpenApiReference
|
||
{
|
||
Type = ReferenceType.SecurityScheme,
|
||
Id = "Bearer"
|
||
}
|
||
},
|
||
new string[] { }
|
||
}
|
||
});
|
||
});
|
||
|
||
var app = builder.Build();
|
||
|
||
app.UseCors("AllowAll");
|
||
|
||
// 配置Swagger
|
||
app.UseSwagger();
|
||
app.UseSwaggerUI();
|
||
|
||
app.UseHttpsRedirection();
|
||
app.UseStaticFiles();
|
||
app.UseRouting();
|
||
app.UseAuthentication();
|
||
|
||
app.UseAuthorization();
|
||
|
||
// 自定义中间件 把404变成200
|
||
app.Use(async (context, next) =>
|
||
{
|
||
await next(); // 先执行后续中间件
|
||
|
||
// 如果响应是 404 且未修改过
|
||
if (context.Response.StatusCode == 404 && !context.Response.HasStarted)
|
||
{
|
||
context.Response.StatusCode = 200; // 改为 200
|
||
context.Response.ContentType = "application/json";
|
||
|
||
// 自定义响应内容
|
||
await context.Response.WriteAsJsonAsync(new ReturnTemplate(404, "未能找到资源吖!", null!));
|
||
}
|
||
});
|
||
|
||
// 控制器路由
|
||
app.MapControllers();
|
||
|
||
app.MapRazorPages();
|
||
|
||
app.Run(); |