71 lines
2.3 KiB
C#
71 lines
2.3 KiB
C#
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||
using Microsoft.IdentityModel.Tokens;
|
||
using MySql.Data.MySqlClient;
|
||
using System.Text;
|
||
|
||
var builder = WebApplication.CreateBuilder(args);
|
||
|
||
// Add services to the container.
|
||
builder.Services.AddControllers();
|
||
|
||
// 添加HttpClientFactory
|
||
builder.Services.AddHttpClient();
|
||
|
||
// 添加数据库连接
|
||
builder.Services.AddScoped<MySqlConnection>(sp => {
|
||
var connectionString = builder.Configuration.GetConnectionString("MySQLConnection");
|
||
return new MySqlConnection(connectionString);
|
||
});
|
||
|
||
builder.Services.AddAuthorization();
|
||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||
.AddJwtBearer(option =>
|
||
{
|
||
string DefaultKey = "B,EZipeApY3cNj3~4RP0UMR=H>9x8.1!E85wmZ]]py2d$Y?5";
|
||
var sec = Encoding.UTF8.GetBytes(builder.Configuration["JWT:SecretKey"] ?? DefaultKey);
|
||
|
||
option.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
|
||
{
|
||
ValidateIssuer = true,
|
||
ValidateAudience = true,
|
||
ValidateLifetime = true,
|
||
|
||
ValidateIssuerSigningKey = true,
|
||
ValidIssuer = builder.Configuration["JwT:Issuer"],
|
||
ValidAudience = builder.Configuration["JwT:Audience"],
|
||
IssuerSigningKey = new SymmetricSecurityKey(sec)
|
||
};
|
||
|
||
option.Events = new JwtBearerEvents
|
||
{
|
||
OnMessageReceived = context =>
|
||
{
|
||
var token = context.Request.Headers["token"].FirstOrDefault();
|
||
if (string.IsNullOrEmpty(token))
|
||
{
|
||
// 如果没有找到 token 头部,则继续检查 Authorization 头部
|
||
token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
|
||
}
|
||
// 如果找到了 token,则将其设置到 HttpContext 中
|
||
if (!string.IsNullOrEmpty(token))
|
||
{
|
||
context.Token = token;
|
||
}
|
||
return Task.CompletedTask;
|
||
}
|
||
};
|
||
});
|
||
|
||
|
||
var app = builder.Build();
|
||
|
||
// Configure the HTTP request pipeline.
|
||
app.UseAuthentication(); // 添加认证中间件
|
||
app.UseAuthorization(); // 使用授权中间件
|
||
|
||
app.UseAuthorization();
|
||
|
||
app.MapControllers();
|
||
|
||
app.Run();
|