/// <summary> /// 处理接口文档的用户认证 /// </summary> /// <param name="app"></param> /// <param name="options"></param> /// <returns></returns> private static IApplicationBuilder UseSwaggerCustomAuth(this IApplicationBuilder app, CustsomSwaggerOptions options) { if (options.AllowAnonymous) { return(app); } var currentAssembly = typeof(CustsomSwaggerOptions).GetTypeInfo().Assembly; app.Use(async(context, next) => { var _method = context.Request.Method.ToLower(); var _path = context.Request.Path.Value; var subPath = string.IsNullOrEmpty(options.AppPath) ? "" : $"/{options.AppPath}"; //发布为虚拟站点时使用 #region 自定义登录页 if (_path.IndexOf($"/{options.RoutePrefix}") != 0) //非访问接口时直接返回 { await next(); return; } else if (_path == $"/{options.RoutePrefix}/login.html") { //登录 if (_method == "get") { var stream = currentAssembly.GetManifestResourceStream($"{currentAssembly.GetName().Name}.login.html"); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); context.Response.ContentType = "text/html;charset=utf-8"; context.Response.StatusCode = StatusCodes.Status200OK; await context.Response.Body.WriteAsync(buffer, 0, buffer.Length); return; } else if (_method == "post") { var userModel = new CustomSwaggerAuth(context.Request.Form["userName"], context.Request.Form["userPwd"]); if (!options.CustomAuthList.Any(e => e.UserName == userModel.UserName && e.UserPwd == userModel.UserPwd)) { await context.Response.WriteAsync("login error!"); return; } var claims = new List <Claim> { new Claim(ClaimTypes.Name, userModel.UserName) }; var identity = new ClaimsIdentity(ConfigurationHelper.SWAGGER_ATUH_COOKIE); identity.AddClaims(claims); var authProperties = new AuthenticationProperties { AllowRefresh = false, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(120), IsPersistent = false, }; await context.SignOutAsync(ConfigurationHelper.SWAGGER_ATUH_COOKIE);//登出 await context.SignInAsync(ConfigurationHelper.SWAGGER_ATUH_COOKIE, new ClaimsPrincipal(identity), authProperties); context.Response.Redirect($"{subPath}/{options.RoutePrefix}"); return; } } else if (_path == $"/{options.RoutePrefix}/logout") { //退出 context.Response.Cookies.Delete(ConfigurationHelper.SWAGGER_ATUH_COOKIE); context.Response.Redirect($"{subPath}/{options.RoutePrefix}/login.html"); return; } #endregion else { if (ConfigurationHelper.CustsomSwaggerOptions.UseAdminAuth) { var authentcationResult = await context.AuthenticateAsync(AdminAuthorizeAttribute.AuthenticationScheme); if (!authentcationResult.Succeeded) { context.Response.Redirect("/Admin/Login/"); return; } } else { var authentcationResult = await context.AuthenticateAsync(ConfigurationHelper.SWAGGER_ATUH_COOKIE); if (!authentcationResult.Succeeded) { context.Response.Redirect($"{subPath}/{options.RoutePrefix}/login.html"); return; } } } await next(); }); return(app); }
private static IApplicationBuilder UseSwaggerCustomAuth(this IApplicationBuilder app, CustsomSwaggerOptions options) { if (options?.SwaggerAuthList.Count == 0) return app; var currentAssembly = typeof(CustsomSwaggerOptions).GetTypeInfo().Assembly; app.Use(async (context, next) => { var _method = context.Request.Method.ToLower(); var _path = context.Request.Path.Value; if (_path.IndexOf($"/{options.RoutePrefix}") != 0) { await next(); return; } else if (_path == $"/{options.RoutePrefix}/login.html") { //登录 if (_method == "get") { var stream = currentAssembly.GetManifestResourceStream($"{currentAssembly.GetName().Name}.login.html"); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); context.Response.ContentType = "text/html;charset=utf-8"; context.Response.StatusCode = StatusCodes.Status200OK; context.Response.Body.Write(buffer, 0, buffer.Length); return; } else if (_method == "post") { var userModel = new CustomSwaggerAuth(context.Request.Form["userName"], context.Request.Form["userPwd"]); if (!options.SwaggerAuthList.Any(e => e.UserName == userModel.UserName && e.UserPwd == userModel.UserPwd)) { await context.Response.WriteAsync("login error!"); return; } //context.Response.Cookies.Append("swagger_auth_name", userModel.UserName); context.Response.Cookies.Append(SWAGGER_ATUH_COOKIE, userModel.AuthStr, new CookieOptions() { Expires = DateTime.Now.AddMonths(1) }); context.Response.Redirect($"/{options.RoutePrefix}"); return; } } else if (_path == $"/{options.RoutePrefix}/logout") { //退出 context.Response.Cookies.Delete(SWAGGER_ATUH_COOKIE); context.Response.Redirect($"/{options.RoutePrefix}/login.html"); return; } else { if (!options.SwaggerAuthList.Any(s => !string.IsNullOrEmpty(s.AuthStr) && s.AuthStr == context.Request.Cookies[SWAGGER_ATUH_COOKIE])) { context.Response.Redirect($"/{options.RoutePrefix}/login.html"); return; } } await next(); }); return app; }