0 votes
by (2.5k points)

In my .NET App, I am using authentication and authorization middleware that is run one after the other like so : 


My main question is, what does authentication and authorization do? What are the differences between the calls and can I have one but not the other?

1 Answer

0 votes
by (2.5k points)

The complete answer for this actually depends on your project and your authentication type. For example, if you are doing Cookie authentication vs JWT authentication etc. But in short it works like this : 

UseAuthentication validates the user and essentially sets up the context to be within that user. So when you call UseAuthentication, it's the process of decoding the JWT, validating it, and setting the HttpContext user. Without it, in your code you could not do something like : 


As an example. So basically think of it as unwrapping your authentication mechanism and setting up the user for the request pipeline. 

UseAuthorization on the other hand is taking that user that you've set up, and running permission and policy checks on whichever endpoint you have requested. If you used UseAuthentication but *not* UseAuthorization, and the user was not logged in and tried to request a secure endpoint, the request would succeed because the call to Authenticate only unwraps the JWT/Cookie, but it doesn't validate the request per say. 

Alternatively, if you make a call to UseAuthorization without UseAuthentication, and make a call to a secure endpoint, then the request would always fail because you are trying to validate a users permissions, but you are not unwrapping the user itself. 

Holistically speaking it works much the same in all programming languages and concepts : 

- Authentication is the act of validating the user is who they are
- Authorization is the act of validating that a user can access the resource

Once you seperate out the two, then the Middleware pipeline in .NET makes more sense. 

Welcome to .NET Q&A, where you can ask questions and receive answers from other members of the community.