24小时一体机服务
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

169 lines
5.5 KiB

using Elight.Logic;
using Elight.Utility;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using SqlSugar;
using System.Data;
using System.Text;
#region builder
var builder = WebApplication.CreateBuilder(args);
var Configuration = builder.Configuration;
// Add services to the container.
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 = "My API", Version = "v1" });
//添加Jwt验证设置
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
new List<string>()
}
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Value: Bearer {token}",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
});
// 添加身份验证服务
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = nameof(ResponseAuthenticationHandler); //401
options.DefaultForbidScheme = nameof(ResponseAuthenticationHandler); //403
})
.AddJwtBearer(options =>
{
// 配置JWT身份验证选项
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration.GetSection("JwtConfiguration:Issuer").Value,
ValidAudience = Configuration.GetSection("JwtConfiguration:Audience").Value,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("JwtConfiguration:Jwtkey").Value)),
ClockSkew = TimeSpan.Zero
};
////重点在于这里;判断是SignalR的路径(https://www.cnblogs.com/fger/p/11811190.html)
options.Events = new JwtBearerEvents
{
OnMessageReceived = (context) =>
{
if (!context.HttpContext.Request.Path.HasValue) return Task.CompletedTask;
//重点在于这里;判断是SignalR的路径
var accessToken = context.HttpContext.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
if (string.IsNullOrWhiteSpace(accessToken) || !path.StartsWithSegments("/ws")) return Task.CompletedTask;
context.Token = accessToken;
return Task.CompletedTask;
},
//此处为权限验证失败后触发的事件
OnChallenge = context =>
{
//此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦,必须
context.HandleResponse();
//自定义自己想要返回的数据结果,我这里要返回的是Json对象,通过引用Newtonsoft.Json库进行转换
var payload = new { StatusCode = 0, Message = "身份认证失败!" };
//自定义返回的数据类型
context.Response.ContentType = "application/json";
//自定义返回状态码,默认为401 我这里改成 200
context.Response.StatusCode = StatusCodes.Status200OK;
//context.Response.StatusCode = StatusCodes.Status401Unauthorized;
//输出Json数据结果
context.Response.WriteAsync(Convert.ToString(payload));
return Task.FromResult(0);
}
};
}).AddScheme<AuthenticationSchemeOptions, ResponseAuthenticationHandler>(nameof(ResponseAuthenticationHandler), o => { });
builder.Services.AddAuthorization();
builder.Services.AddHttpContextAccessor();
builder.Services.TryAddSingleton<User, User>(); //jwt
builder.Services.TryAddSingleton<WriteSysLog, WriteSysLog>(); //WriteSysLog
builder.Services.AddScoped<SqlSugarClient>(sp =>
{
var connectionString = Configuration.GetSection("ConnectionStrings:MySQLConnString").Value;
var db = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = connectionString,
DbType = SqlSugar.DbType.MySql,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
return db;
});
#endregion
#region APP
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
//路由
app.UseRouting();
app.UseAuthentication(); // 启用身份验证中间件
app.UseAuthorization(); // 启用授权中间件
//app.MapControllers();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
#region swagger
app.UseSwagger();// 启用Swagger中间件
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});
#endregion
#region websockets配置
app.UseWebSockets(new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromMinutes(120)
});
//app.UseMiddleware<WebSocketMiddleware>();
#endregion
app.Run();
#endregion