0

I am trying to build my custom authorization middle ware in ASP.Net Core. Which checks if the called action (method in controller class) is tagged by [Authorize] attribute. I still do not have good ideas how can I implement that.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.Use((context, next) =>
    {
        // if (THE CALLED ACTION HAS [Authorize] attribute)
        //     DO SOMETHING...
        return next();
    });

    app.UseMvcWithDefaultRoute();     
}

Could some one give me any hint to implement the commented condition?

11
  • That early in pipeline the action has not been determined as yet so there is not even an action to check for attributes. Commented Nov 7, 2017 at 2:06
  • @Nkosi, ok so is it some how possible to get that working by implementing my own middle ware? Commented Nov 7, 2017 at 2:07
  • 1
    I would suggest reading up here learn.microsoft.com/en-us/aspnet/core/fundamentals/… Commented Nov 7, 2017 at 2:09
  • @Nkosi, actually I have just finished reading it before asking, but I still have not got it yet, sorry. Could you give any related hint? So how does MVC with its build in identity knows that something is tagged with [Authorize] attribute, when it is called before using MVC? I appreciate any hint which helps me to implement that. Commented Nov 7, 2017 at 2:16
  • 1
    filters are the way to go Commented Nov 7, 2017 at 3:24

1 Answer 1

1

In general, if you need to check whether the action has an attribute, you need to use the action filter, not middleware.

Why? Cause action methods are part of MVC middleware and so action filters are. While standard middlewares don't know about MVC concept.

Sign up to request clarification or add additional context in comments.

3 Comments

How to check if the current called action has XZY attribute inside using the filter? Could you post some lines code please?
@MohammedNoureldin look into SO Checking for an attribute in an action filter
Ah perfect! Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.