具有ASPNET核心的自定义授权过滤器 [英] Custom Authorize filter with aspnet core

查看:51
本文介绍了具有ASPNET核心的自定义授权过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自定义的授权过滤器,该过滤器将允许我自动授权来自本地主机的请求(将用于我的测试).

我为Asp.net找到了以下内容,但是在将其移植到asp.net核心时遇到了麻烦.

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Request.Url.IsLoopback)
        {
            // It was a local request => authorize the guy
            return true;
        }

        return base.AuthorizeCore(httpContext);
    }
}

如何将其移植到asp.net核心?

解决方案

您可以创建一个中间件,在其中可以自动授权来自本地主机的请求.

public class MyAuthorize
{
   private readonly RequestDelegate _next;
   public MyAuthorize(RequestDelegate next)
   {
      _next = next;
   }

   public async Task Invoke(HttpContext httpContext)
   {
     // authorize request source here.

    await _next(httpContext);
   }
}

然后创建一个扩展方法

public static class CustomMiddleware
{
        public static IApplicationBuilder UseMyAuthorize(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyAuthorize>();
        }
}

,最后将其添加到启动Configure方法中.

app.UseMyAuthorize();

Asp.Net Core没有IsLoopback属性.这是解决此问题的方法 https://stackoverflow.com/a/41242493/2337983

您还可以在此处阅读有关中间件的更多信息 >

Hi I am trying to create a custom authorize filter that will allow me to authorize requests coming from localhost automatically (which will be used for my tests).

I found the following one for Asp.net however am having trouble porting it to asp.net core.

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Request.Url.IsLoopback)
        {
            // It was a local request => authorize the guy
            return true;
        }

        return base.AuthorizeCore(httpContext);
    }
}

How can I port this to asp.net core?

解决方案

You can create a middleware in which you can authorize requests coming from localhost automatically.

public class MyAuthorize
{
   private readonly RequestDelegate _next;
   public MyAuthorize(RequestDelegate next)
   {
      _next = next;
   }

   public async Task Invoke(HttpContext httpContext)
   {
     // authorize request source here.

    await _next(httpContext);
   }
}

Then create an extension method

public static class CustomMiddleware
{
        public static IApplicationBuilder UseMyAuthorize(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyAuthorize>();
        }
}

and finally add it in startup Configure method.

app.UseMyAuthorize();

Asp.Net Core did not have IsLoopback property. Here is a work around for this https://stackoverflow.com/a/41242493/2337983

You can also read more about Middleware here

这篇关于具有ASPNET核心的自定义授权过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆