Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Authorize filter with aspnet core

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?

like image 871
Jamesla Avatar asked Dec 23 '16 00:12

Jamesla


1 Answers

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

like image 135
Ahmar Avatar answered Sep 30 '22 20:09

Ahmar