AlirezaEiji
AlirezaEiji

Reputation: 29

Relation between Authorization middleware and filter Asp.net core

I was watching tutorial about Asp .net core and I was wondering the difference between filters and middleware and after some research I found the answer of my question that middleware pipeline is proceed before filter pipeline. but I face with strange situation! when I use [Authorize] before any action method as it is a filter what is the purpose of using authentication and authorization middleware? because the filter is executed after middlewares.

I mean the main question is that what is the purpose of using authentication and authorization middlerware and what is the flow of processing Request when we use [Authorize] before any action method?

Upvotes: 1

Views: 4599

Answers (3)

dot19
dot19

Reputation: 21

  • Authentication Middleware: Authenticates the user and sets HttpContext.User.
  • Authorization Middleware: Enforces global authorization policies.
  • [Authorize] Filter: Ensures the authenticated user is authorized to access the specific action or controller.

Upvotes: 2

Randa
Randa

Reputation: 88

Actually, the authorization filter is part of the authorization middleware's responsibilities. It will not work if the authorization middleware is missing and an exception will be thrown at runtime.

What happens is whenever an HTTP request comes, it will go through the middleware pipeline. The authentication middleware will work on authenticating the user (that has sent the request) using a previously configured authentication scheme such as cookie or token. The authorization middleware then will work on comparing the claims of the user, that are existing inside the provided token or cookie, with the security requirements that are specified through the [Authorize] attribute. If the authorization failed, the HTTP request will be filtered out and the access to the requested action method will be prevented.

This is a summary about how things work, hope that helps!

Upvotes: 3

Mohammad Barbast
Mohammad Barbast

Reputation: 2049

You have a misunderstanding of the concepts.

Middleware is piece of code that's placed into an app pipeline to handle requests and responses.

Filter is not a middleware, it is piece of code that can be run before or after specific stages in UseEndpoints middleware (razor pages or controllers). you can think of filters as a semi-Middleware that is placed in a smaller pipeline handling endpoints.

I recommend you refer to Filters and Middleware for more information.

Upvotes: 0

Related Questions