145 lines
5.4 KiB
C#
145 lines
5.4 KiB
C#
|
|
using IM_API.Configs;
|
|
using IM_API.Filters;
|
|
using IM_API.Hubs;
|
|
using IM_API.Models;
|
|
using IM_API.Tools;
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using StackExchange.Redis;
|
|
using System.Text;
|
|
|
|
namespace IM_API
|
|
{
|
|
public class Program
|
|
{
|
|
public static void Main(string[] args)
|
|
{
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
// Add services to the container.
|
|
IConfiguration configuration = new ConfigurationBuilder()
|
|
.SetBasePath(Directory.GetCurrentDirectory())
|
|
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
|
|
.Build();
|
|
string conStr = configuration.GetConnectionString("DefaultConnection")!;
|
|
string redisConStr = configuration.GetConnectionString("Redis");
|
|
//注入数据库上下文
|
|
builder.Services.AddDbContext<ImContext>(options =>
|
|
{
|
|
options.UseMySql(conStr,ServerVersion.AutoDetect(conStr));
|
|
});
|
|
//注入redis
|
|
var redis = ConnectionMultiplexer.Connect(redisConStr);
|
|
builder.Services.AddSingleton<IConnectionMultiplexer>(redis);
|
|
|
|
builder.Services.AddRabbitMQ(configuration.GetSection("RabbitMqOptions").Get<RabbitMqOptions>());
|
|
|
|
builder.Services.AddAllService(configuration);
|
|
|
|
builder.Services.AddSignalR();
|
|
//允许所有来源(跨域)
|
|
builder.Services.AddCors(options =>
|
|
{
|
|
options.AddDefaultPolicy(policy =>
|
|
{
|
|
policy.AllowAnyHeader()
|
|
.AllowAnyMethod()
|
|
.AllowAnyHeader()
|
|
.AllowCredentials()
|
|
.SetIsOriginAllowed(origin =>
|
|
{
|
|
// 允许所有来自本地或特定网段的请求
|
|
var host = new Uri(origin).Host;
|
|
return host == "localhost" || host.StartsWith("192.168.");
|
|
});
|
|
});
|
|
});
|
|
//凭证处理
|
|
builder.Services.AddAuthentication(options =>
|
|
{
|
|
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
|
})
|
|
.AddJwtBearer(options =>
|
|
{
|
|
//https非必须
|
|
options.RequireHttpsMetadata = false;
|
|
//保存token
|
|
options.SaveToken = true;
|
|
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
|
|
{
|
|
//验证签发者
|
|
ValidateIssuer = true,
|
|
ValidIssuer = configuration["Jwt:Issuer"],
|
|
//验证受众
|
|
ValidateAudience = true,
|
|
ValidAudience = configuration["Jwt:Audience"],
|
|
//验证签名密钥
|
|
ValidateIssuerSigningKey = true,
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"])),
|
|
//时间偏差容忍
|
|
ValidateLifetime = true,
|
|
ClockSkew = TimeSpan.FromSeconds(30)
|
|
|
|
|
|
};
|
|
//websocket token凭证处理
|
|
options.Events = new JwtBearerEvents {
|
|
OnMessageReceived = context =>
|
|
{
|
|
var accessToken = context.Request.Query["access_token"];
|
|
if (!string.IsNullOrEmpty(accessToken))
|
|
{
|
|
context.Token = accessToken;
|
|
}
|
|
return Task.CompletedTask;
|
|
},
|
|
OnAuthenticationFailed = context =>
|
|
{
|
|
Console.WriteLine("Authentication failed: " + context.Exception.Message);
|
|
return Task.CompletedTask;
|
|
}
|
|
};
|
|
});
|
|
builder.Services.AddControllers(options =>
|
|
{
|
|
options.Filters.Add<GlobalExceptionFilter>();
|
|
}).AddJsonOptions(options =>
|
|
{
|
|
// 保持 ISO 8601 格式
|
|
options.JsonSerializerOptions.Converters.Add(new UtcDateTimeConverter());
|
|
});
|
|
builder.Services.AddModelValidation(configuration);
|
|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
|
builder.Services.AddEndpointsApiExplorer();
|
|
builder.Services.AddSwaggerGen();
|
|
|
|
var app = builder.Build();
|
|
|
|
app.UseCors();
|
|
|
|
// Configure the HTTP request pipeline.
|
|
if (app.Environment.IsDevelopment())
|
|
{
|
|
app.UseSwagger();
|
|
app.UseSwaggerUI();
|
|
}
|
|
|
|
app.UseHttpsRedirection();
|
|
|
|
app.UseAuthentication();
|
|
app.UseAuthorization();
|
|
|
|
|
|
|
|
app.MapControllers();
|
|
|
|
app.MapHub<ChatHub>("/chat").RequireCors();
|
|
|
|
app.Run();
|
|
}
|
|
}
|
|
}
|