ASP.NET Core Authentication & Authorization 1 — Questions and Answers
Question 1: Which attribute restricts access to authenticated users only in ASP.NET Core?
- [Authorize] (Correct answer)
- [Authenticated]
- [RequireLogin]
- [Protected]
Correct answer: [Authorize]
[Authorize] applies the default authorization policy, denying access to unauthenticated users with a 401 or redirect.
Question 2: What does [AllowAnonymous] do when placed on an action inside an [Authorize] controller?
- Overrides the controller-level authorization, allowing unauthenticated access to that action (Correct answer)
- Has no effect inside an [Authorize] controller
- Requires anonymous authentication only
- Logs anonymous access for audit purposes
Correct answer: Overrides the controller-level authorization, allowing unauthenticated access to that action
[AllowAnonymous] takes precedence over any [Authorize] attributes, allowing the action to bypass authentication checks.
Question 3: Which middleware must be added before UseAuthorization() for authentication to work?
- UseAuthentication() (Correct answer)
- UseIdentity()
- UseLogin()
- UseJwt()
Correct answer: UseAuthentication()
UseAuthentication() must precede UseAuthorization() so that user identity is established before authorization policies are evaluated.
Question 4: What is the purpose of JWT Bearer authentication in ASP.NET Core APIs?
- To validate tokens sent in the Authorization header and set the user identity (Correct answer)
- To store user sessions on the server
- To redirect users to a login page
- To encrypt the request body
Correct answer: To validate tokens sent in the Authorization header and set the user identity
JWT Bearer middleware validates the signed JSON Web Token and populates HttpContext.User with claims from the token payload.
Question 5: Which method adds ASP.NET Core Identity to the application?
- services.AddIdentity<TUser, TRole>() (Correct answer)
- services.UseIdentity()
- services.RegisterIdentity()
- services.AddUserManagement()
Correct answer: services.AddIdentity<TUser, TRole>()
AddIdentity<TUser, TRole>() registers Identity services including user management, password hashing, and role management.
Question 6: What does [Authorize(Roles = "Admin")] do in ASP.NET Core?
- Restricts the action to users who have the Admin role claim (Correct answer)
- Creates a new role named Admin
- Requires the Admin policy to be defined
- Restricts access to the admin area only
Correct answer: Restricts the action to users who have the Admin role claim
The Roles parameter checks the user's role claims and returns 403 Forbidden if the user does not have the specified role.
Which attribute restricts access to authenticated users only in ASP.NET Core?