ASP.NET Core中AddAuthentication与AddAuthorization的区别及作用解析
Great question! Let's break down the key differences between services.AddAuthentication() and services.AddAuthorization() in ASP.NET Core, and walk through exactly what your code is doing.
services.AddAuthentication(): Handling "Who are you?" This method sets up authentication in your app—this is the process of verifying that a user is who they claim to be. Think of it like checking someone's ID card before letting them into a building.
In your code, you're:
- Setting
JwtBearerDefaults.AuthenticationSchemeas the default authentication scheme, meaning your app will use JWT (JSON Web Tokens) to verify user identities. - Calling
.AddJwtBearer()to configure strict JWT validation rules:ValidateIssuer = true: Ensures the token was issued by your trusted source (theValidIssuervalue you defined).ValidateAudience = true: Confirms the token was specifically generated for your application (matching yourValidAudience).ValidateLifetime = true: Checks that the token hasn't expired.ValidateIssuerSigningKey = true: Verifies the token's signature matches your secretIssuerSigningKey, so you know the token hasn't been tampered with.ClockSkew = TimeSpan.Zero: Removes any default time buffer for token expiration—so the token becomes invalid the second it expires, no grace period.
All these settings work together to confirm incoming JWT tokens are legitimate and tied to a real, valid user.
This method sets up authorization—the process of determining if an authenticated user has permission to access a specific resource or perform an action. It's like checking if the person with the ID card is allowed to enter a restricted office floor after they've been let into the building.
Your services.AddAuthorization() call initializes ASP.NET Core's default authorization system. Once this is in place, you can:
- Use the
[Authorize]attribute on controllers/actions to restrict access to only authenticated users. - Add role-based access, like
[Authorize(Roles = "Admin")], to limit access to users with specific roles. - Create custom authorization policies (e.g., requiring a specific claim in the JWT) to enforce more granular access rules.
Without calling AddAuthorization(), you won't be able to use any of these access-control features—even if you have authentication fully set up.
Authentication is a prerequisite for authorization. Your app first uses the settings from AddAuthentication() to confirm a user's identity, then uses AddAuthorization() to decide if that user is allowed to do what they're trying to do.
To put it plainly:
- Authentication = "Prove you're who you say you are"
- Authorization = "Prove you're allowed to do this"
内容的提问来源于stack exchange,提问作者hawks

