1

I want to create a custom AuthorizeAttribute that does the following:

  • If the requested URL contains the query parameter id, normal authorization is required
  • If the requested URL does not contain the query parameter id, no authorization is required

Reading https://docs.microsoft.com/en-us/aspnet/core/security/authorization/iauthorizationpolicyprovider?view=aspnetcore-3.1 does not make things very clear in this particular case.

Reading How do you create a custom AuthorizeAttribute in ASP.NET Core? also does not make things clear as it depends on claims.

HelloWorld
  • 2,271
  • 21
  • 34
  • Another way to look at it is that authenticated users are granted the "Can access endpoints without passing an ID in the URL" permission, a.k.a. claim. There's something to be said for [sticking to patterns that are familiar to people](https://en.wikipedia.org/wiki/Principle_of_least_astonishment). – John Wu Mar 03 '20 at 10:07

1 Answers1

2

You can simply create Authorization Filter

public class CustomAuthorizationFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            string id = context.HttpContext.Request.Query["id"]?.ToString();

            if (!string.IsNullOrEmpty(id))
            {
                // Authorization logic
            }
        }
    }
Voodoo
  • 967
  • 1
  • 7
  • 15
  • In the AuthorizeAttribute, the user gets redirected to login if unauthorized. Is it possible to achieve the same behaviour in an IAuthorizationFilter? I mean without hard coding the redirect url (AuthorizeAttribute figures it out automatically). – HelloWorld Mar 03 '20 at 12:36
  • You mean to say after login successfully it will redirect to the request url before? – Voodoo Mar 03 '20 at 14:02
  • No, I mean before login. If the above attribute example; if it turns out that the user was not authorized, I need to redirect to the login page (according to ConfigureServices, e.g. services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o => o.LoginPath = "/login")). The Authorize attribute seems to do this automatically. Of course I could return a redirect manually and duplicate the login path string, but if it's possible to do it the way the Authorize attribute does it... :) – HelloWorld Mar 04 '20 at 07:28