YiAbpWebModule.cs 17.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
using System.Globalization;
using System.Text;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading.RateLimiting;
using Hangfire;
using Hangfire.MemoryStorage;
using Hangfire.Redis.StackExchange;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using StackExchange.Redis;
using Volo.Abp.AspNetCore.Auditing;
using Volo.Abp.AspNetCore.Authentication.JwtBearer;
using Volo.Abp.AspNetCore.ExceptionHandling;
using Volo.Abp.AspNetCore.MultiTenancy;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.AntiForgery;
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.Auditing;
using Volo.Abp.Autofac;
using Volo.Abp.BackgroundWorkers;
using Volo.Abp.Caching;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Swashbuckle;
using Swashbuckle.AspNetCore.SwaggerGen;
using Yi.Abp.Application;
using Yi.Abp.SqlsugarCore;
using Yi.Framework.AspNetCore;
using Yi.Framework.AspNetCore.Authentication.OAuth;
using Yi.Framework.AspNetCore.Authentication.OAuth.Gitee;
using Yi.Framework.AspNetCore.Authentication.OAuth.QQ;
using Yi.Framework.AspNetCore.Microsoft.AspNetCore.Builder;
using Yi.Framework.AspNetCore.Microsoft.Extensions.DependencyInjection;
using Yi.Framework.AspNetCore.UnifyResult;
using Yi.Framework.BackgroundWorkers.Hangfire;
using Yi.Framework.Core.Json;
using Yi.Framework.Rbac.Application;
using Yi.Framework.Rbac.Domain.Authorization;
using Yi.Framework.Rbac.Domain.Shared.Consts;
using Yi.Framework.Rbac.Domain.Shared.Options;
using Yi.Framework.TenantManagement.Application;
using Antis.Erp.Application;

namespace Yi.Abp.Web
{
    [DependsOn(
        typeof(YiAbpSqlSugarCoreModule),
        typeof(YiAbpApplicationModule),
        typeof(AntisErpApplicationModule),
        typeof(AbpAspNetCoreMultiTenancyModule),
        typeof(AbpAspNetCoreMvcModule),

        typeof(AbpSwashbuckleModule),
        typeof(AbpAspNetCoreSerilogModule),
        typeof(AbpAuditingModule),
        typeof(AbpAspNetCoreAuthenticationJwtBearerModule),
        typeof(YiFrameworkAspNetCoreModule),
        typeof(YiFrameworkAspNetCoreAuthenticationOAuthModule),

        typeof(YiFrameworkBackgroundWorkersHangfireModule),
        typeof(AbpAutofacModule)
    )]
    public class YiAbpWebModule : AbpModule
    {
        private const string DefaultCorsPolicyName = "Default";

        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            //动态Api-改进在pre中配置,启动更快
            PreConfigure<AbpAspNetCoreMvcOptions>(options =>
            {
                options.ConventionalControllers.Create(typeof(YiFrameworkRbacApplicationModule).Assembly, options => options.RemoteServiceName = "用户权限接口");
                options.ConventionalControllers.Create(typeof(YiAbpApplicationModule).Assembly, options => options.RemoteServiceName = "default");
                options.ConventionalControllers.Create(typeof(YiFrameworkTenantManagementApplicationModule).Assembly, options => options.RemoteServiceName = "租户管理接口");
                options.ConventionalControllers.Create(typeof(AntisErpApplicationModule).Assembly, options => options.RemoteServiceName = "安第斯测试接口");
                //统一前缀
                options.ConventionalControllers.ConventionalControllerSettings.ForEach(x => x.RootPath = "api/app");
            });
        }

        public override Task ConfigureServicesAsync(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();
            var host = context.Services.GetHostingEnvironment();
            var service = context.Services;

            //本地开发环境,禁用作业执行
            if (host.IsDevelopment())
            {
                Configure<AbpBackgroundWorkerOptions>(options =>
                {
                    options.IsEnabled = false;
                });
            }

            //请求日志
            Configure<AbpAuditingOptions>(options =>
            {
                //默认关闭,开启会有大量的审计日志
                options.IsEnabled = false;
            });
            //忽略审计日志路径
            Configure<AbpAspNetCoreAuditingOptions>(options =>
            {
                options.IgnoredUrls.Add("/api/app/file/");
                options.IgnoredUrls.Add("/hangfire");
            });

            //采用furion格式的规范化api,默认不开启,使用abp优雅的方式
            //前置:需要将管道工作单元前加上app.Properties.Add("_AbpExceptionHandlingMiddleware_Added",false);
            //你没看错。。。
            service.AddFurionUnifyResultApi();

            //配置错误处理显示详情
            Configure<AbpExceptionHandlingOptions>(options => { options.SendExceptionsDetailsToClients = true; });

            //【NewtonsoftJson严重问题!!!!!逆天】设置api格式,留给后人铭记
            // service.AddControllers().AddNewtonsoftJson(options =>
            // {
            //     options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            //     options.SerializerSettings.Converters.Add(new StringEnumConverter());
            // });

            //请使用微软的,注意abp date又包了一层,采用DefaultJsonTypeInfoResolver统一覆盖
            Configure<JsonOptions>(options =>
            {
                options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver();
                options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
                options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
            });

            //设置缓存不要过期,默认滑动20分钟
            Configure<AbpDistributedCacheOptions>(cacheOptions =>
            {
                cacheOptions.GlobalCacheEntryOptions.SlidingExpiration = null;
                //缓存key前缀
                cacheOptions.KeyPrefix = "Yi:";
            });


            Configure<AbpAntiForgeryOptions>(options => { options.AutoValidate = false; });

            //Swagger
            context.Services.AddYiSwaggerGen<YiAbpWebModule>(options =>
            {
                options.SwaggerDoc("default",
                    new OpenApiInfo { Title = "Yi.Framework.Abp", Version = "v1", Description = "集大成者" });
            });

            // 根据配置决定是否移除租户参数
            // 如果未启用多租户,则在 Swagger 中移除 __tenant 参数
            var enabledSaasMultiTenancy = configuration.GetSection("DbConnOptions:EnabledSaasMultiTenancy").Get<bool>();
            if (!enabledSaasMultiTenancy)
            {
                // 在所有 Swagger 配置完成后,添加过滤器来移除租户参数
                // PostConfigure 确保在 ConfigureCustomFilters 之后执行
                context.Services.PostConfigure<SwaggerGenOptions>(options =>
                {
                    options.OperationFilter<RemoveTenantParameterFilter>();
                });
            }

            //跨域
            context.Services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicyName, builder =>
                {
                    builder
                        .WithOrigins(
                            configuration["App:CorsOrigins"]!
                                .Split(";", StringSplitOptions.RemoveEmptyEntries)
                                .Select(o => o.RemovePostFix("/"))
                                .ToArray()
                        )
                        .WithAbpExposedHeaders()
                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });
            });

            //配置多租户
            Configure<AbpTenantResolveOptions>(options =>
            {
                //基于cookie jwt不好用,有坑
                options.TenantResolvers.Clear();
                options.TenantResolvers.Add(new HeaderTenantResolveContributor());
                //options.TenantResolvers.Add(new HeaderTenantResolveContributor());
                //options.TenantResolvers.Add(new CookieTenantResolveContributor());
                //options.TenantResolvers.RemoveAll(x => x.Name == CookieTenantResolveContributor.ContributorName);
            });

            //配置Hangfire定时任务存储,开启redis后,优先使用redis
            var redisConfiguration = configuration["Redis:Configuration"];
            context.Services.AddHangfire(config =>
            {
                var redisEnabled = configuration.GetSection("Redis").GetValue<bool>("IsEnabled");
                if (redisEnabled)
                {
                    var jobDb = configuration.GetSection("Redis").GetValue<int>("JobDb");
                    config.UseRedisStorage(
                        ConnectionMultiplexer.Connect(redisConfiguration),
                        new RedisStorageOptions()
                        {
                            Db = jobDb,
                            InvisibilityTimeout = TimeSpan.FromHours(1), //JOB允许执行1小时
                            Prefix = "Yi:HangfireJob:"
                        }).WithJobExpirationTimeout(TimeSpan.FromHours(1));
                }
                else
                {
                    config.UseMemoryStorage();
                }
            });

            //速率限制
            //每60秒限制100个请求,滑块添加,分6段
            service.AddRateLimiter(_ =>
            {
                _.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
                _.OnRejected = (context, _) =>
                {
                    if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
                    {
                        context.HttpContext.Response.Headers.RetryAfter =
                            ((int)retryAfter.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo);
                    }

                    context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests;
                    context.HttpContext.Response.WriteAsync("Too many requests. Please try again later.");

                    return new ValueTask();
                };

                //全局使用,链式表达式
                _.GlobalLimiter = PartitionedRateLimiter.CreateChained(
                    PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
                    {
                        var userAgent = httpContext.Request.Headers.UserAgent.ToString();

                        return RateLimitPartition.GetSlidingWindowLimiter
                        (userAgent, _ =>
                            new SlidingWindowRateLimiterOptions
                            {
                                PermitLimit = 1000,
                                Window = TimeSpan.FromSeconds(60),
                                SegmentsPerWindow = 6,
                                QueueProcessingOrder = QueueProcessingOrder.OldestFirst
                            });
                    }));
            });


            //jwt鉴权
            var jwtOptions = configuration.GetSection(nameof(JwtOptions)).Get<JwtOptions>();
            var refreshJwtOptions = configuration.GetSection(nameof(RefreshJwtOptions)).Get<RefreshJwtOptions>();

            context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        RoleClaimType = "Roles",
                        ClockSkew = TimeSpan.Zero,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = jwtOptions.Issuer,
                        ValidAudience = jwtOptions.Audience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecurityKey))
                    };
                    options.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = messageContext =>
                        {
                            //优先Query中获取,再去cookies中获取
                            var accessToken = messageContext.Request.Query["access_token"];
                            if (!string.IsNullOrEmpty(accessToken))
                            {
                                messageContext.Token = accessToken;
                            }
                            else
                            {
                                if (!messageContext.Request.Headers.ContainsKey("Authorization") &&
                                    messageContext.Request.Cookies.TryGetValue("Token", out var cookiesToken))
                                {
                                    messageContext.Token = cookiesToken;
                                }
                            }

                            return Task.CompletedTask;
                        }
                    };
                })
                .AddJwtBearer(TokenTypeConst.Refresh, options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ClockSkew = TimeSpan.Zero,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = refreshJwtOptions.Issuer,
                        ValidAudience = refreshJwtOptions.Audience,
                        IssuerSigningKey =
                            new SymmetricSecurityKey(Encoding.UTF8.GetBytes(refreshJwtOptions.SecurityKey))
                    };
                    options.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = messageContext =>
                        {
                            var headerRefreshToken = messageContext.Request.Headers["refresh_token"];
                            if (!string.IsNullOrEmpty(headerRefreshToken))
                            {
                                messageContext.Token = headerRefreshToken;
                                return Task.CompletedTask;
                            }

                            var queryRefreshToken = messageContext.Request.Query["refresh_token"];
                            if (!string.IsNullOrEmpty(queryRefreshToken))
                            {
                                messageContext.Token = queryRefreshToken;
                            }

                            return Task.CompletedTask;
                        }
                    };
                })
                .AddQQ(options => { configuration.GetSection("OAuth:QQ").Bind(options); })
                .AddGitee(options => { configuration.GetSection("OAuth:Gitee").Bind(options); });

            //授权
            context.Services.AddAuthorization();


            return Task.CompletedTask;
        }


        public override async Task OnApplicationInitializationAsync(ApplicationInitializationContext context)
        {
            var service = context.ServiceProvider;
            var env = context.GetEnvironment();
            var app = context.GetApplicationBuilder();

            app.UseRouting();

            //跨域
            app.UseCors(DefaultCorsPolicyName);

            if (!env.IsDevelopment())
            {
                //速率限制
                app.UseRateLimiter();
            }


            //无感token,先刷新再鉴权
            app.UseRefreshToken();

            //鉴权
            app.UseAuthentication();

            //多租户
            app.UseMultiTenancy();

            //swagger
            app.UseYiSwagger();

            //请求处理
            app.UseApiInfoHandling();

            //静态资源
            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = "/api/app/wwwroot",
                // 可以在这里添加或修改MIME类型映射  
                ContentTypeProvider = new FileExtensionContentTypeProvider
                {
                    Mappings =
                    {
                        [".wxss"] = "text/css"
                    }
                }
            });
            app.UseDefaultFiles();
            app.UseDirectoryBrowser("/api/app/wwwroot");

            app.Properties.Add("_AbpExceptionHandlingMiddleware_Added", false);
            //工作单元
            app.UseUnitOfWork();

            //授权
            app.UseAuthorization();

            //审计日志
            app.UseAuditing();

            //日志记录
            app.UseAbpSerilogEnrichers();

            //Hangfire定时任务面板,可配置授权,意框架支持jwt
            app.UseAbpHangfireDashboard("/hangfire",
                options =>
                {
                    options.AsyncAuthorization = new[] { new YiTokenAuthorizationFilter(app.ApplicationServices) };
                });

            //终节点
            app.UseConfiguredEndpoints();
        }
    }

    /// <summary>
    /// 移除租户参数的过滤器
    /// </summary>
    public class RemoveTenantParameterFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.Parameters != null)
            {
                operation.Parameters.RemoveAll(p => p.Name == "__tenant");
            }
        }
    }
}