¶Ô±ÈÐÂÎļþ |
| | |
| | | using Microsoft.AspNetCore.Builder; |
| | | using Microsoft.AspNetCore.Http; |
| | | using System; |
| | | using System.Collections.Generic; |
| | | using System.Linq; |
| | | using System.Net; |
| | | using System.Text; |
| | | using System.Threading.Tasks; |
| | | |
| | | namespace WIDESEA_Core.Middlewares |
| | | { |
| | | public class SwaggerAuthMiddleware |
| | | { |
| | | |
| | | private readonly RequestDelegate next; |
| | | |
| | | public SwaggerAuthMiddleware(RequestDelegate next) |
| | | { |
| | | this.next = next; |
| | | } |
| | | |
| | | public async Task InvokeAsync(HttpContext context) |
| | | { |
| | | // ä¹å¯ä»¥æ ¹æ®æ¯å¦æ¯æ¬å°å夿 IsLocalRequest |
| | | if (context.Request.Path.Value.ToLower().Contains("index.html")) |
| | | { |
| | | // 夿æéæ¯å¦æ£ç¡® |
| | | if (IsAuthorized(context)) |
| | | { |
| | | await next.Invoke(context); |
| | | return; |
| | | } |
| | | |
| | | // æ æéï¼è·³è½¬swaggerç»å½é¡µ |
| | | context.Response.Redirect("/swg-login.html"); |
| | | } |
| | | else |
| | | { |
| | | await next.Invoke(context); |
| | | } |
| | | } |
| | | |
| | | public bool IsAuthorized(HttpContext context) |
| | | { |
| | | // 使ç¨sessionæ¨¡å¼ |
| | | // å¯ä»¥ä½¿ç¨å
¶ä»ç |
| | | return context.Session.GetString("swagger-code") == "success"; |
| | | } |
| | | |
| | | /// <summary> |
| | | /// 夿æ¯ä¸æ¯æ¬å°è®¿é® |
| | | /// æ¬å°ä¸ç¨swaggeræ¦æª |
| | | /// </summary> |
| | | /// <param name="context"></param> |
| | | /// <returns></returns> |
| | | public bool IsLocalRequest(HttpContext context) |
| | | { |
| | | if (context.Connection.RemoteIpAddress == null && context.Connection.LocalIpAddress == null) |
| | | { |
| | | return true; |
| | | } |
| | | if (context.Connection.RemoteIpAddress.Equals(context.Connection.LocalIpAddress)) |
| | | { |
| | | return true; |
| | | } |
| | | if (IPAddress.IsLoopback(context.Connection.RemoteIpAddress)) |
| | | { |
| | | return true; |
| | | } |
| | | return false; |
| | | } |
| | | } |
| | | public static class SwaggerAuthorizeExtensions |
| | | { |
| | | public static IApplicationBuilder UseSwaggerAuthorized(this IApplicationBuilder builder) |
| | | { |
| | | return builder.UseMiddleware<SwaggerAuthMiddleware>(); |
| | | } |
| | | } |
| | | } |