hawks
hawks

Reputation: 931

What is the difference between services.AddAuthentication() and services.AddAuthorization() in asp net core?

I have the following code and i want to understand what is the difference between those two extension methods. What each one do?

services.AddAuthentication (JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer (options => options.TokenValidationParameters = new TokenValidationParameters {
                ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ClockSkew = TimeSpan.Zero,
                    ValidIssuer = Issuer,
                    ValidAudience = Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(secret)
            });

            services.AddAuthorization();

Thanks,

Upvotes: 6

Views: 17811

Answers (2)

Hassan Faghihi
Hassan Faghihi

Reputation: 2021

It comes from AAA (triple A): Authentication, Authorization, Access

Authentication: When You are authenticated and the system knows who you are. Authorization: when the system knows which resources you should have access to. Access: when the system actually gives you access.

So if you want to access a resource called /api/GetData

  1. System read your session data, cookie, token, or whatever key you provided to find out who you are.

  2. The system check the policy/role/claims etc to find out if you have required permissions.

  3. you go to the GetData and access the resource, now the rest is up to resource to what data it gives you, but the access is granted to this point.

Note: in .NET when you call Add... by convention you are registering a class into injection services.

But when you call Use..., you are placing it into the processing pipeline, so the order of Add... is not important, but the order of Use... is, it should come after routing, why I'm not sure, then first you should use Authentication, then Authorization, and then Controller/Minimal API/Page mapper, because your identity, should first be available, so you can then now your role, and then they should be available for the controller be able to use them.

Upvotes: 0

LeBoucher
LeBoucher

Reputation: 406

If you know the differences between the terms, then maybe the best way to understand the differences between the methods is to look at the source code and see what services are registered.

AddAuthentication

AddAuthorization

Upvotes: -10

Related Questions