You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
using System.Net ;
using System.Threading.Tasks ;
using EntrustSettle.Common.Swagger ;
using Microsoft.AspNetCore.Builder ;
using Microsoft.AspNetCore.Http ;
namespace EntrustSettle.Extensions.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 ( "swagger_index.html" ) )
{
// 判断权限是否正确
if ( IsAuthorized ( context ) )
{
await next . Invoke ( context ) ;
return ;
}
// 无权限, 跳转swagger登录页
context . RedirectSwaggerLogin ( ) ;
}
else
{
await next . Invoke ( context ) ;
}
}
public bool IsAuthorized ( HttpContext context )
{
// 使用session模式
// 可以使用其他的
return context . IsSuccessSwagger ( ) ;
}
/// <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 > ( ) ;
}
}
}