Advertisement

Authorization interview questions and answers

15 Authorization interview questions for ASP.NET Core roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q11 Advanced Save

How do you unit test custom authorization handlers in isolation, without needing a full HTTP request pipeline?

Construct an AuthorizationHandlerContext directly with a test ClaimsPrincipal, the requirement instance, and (for resource-based handlers) a test resource object, then call the handler's HandleRequirementAsync method directly and assert on context.HasSucceeded -- testing the authorization logic in isolation without spinning up a full ASP.NET Core test server.
[Fact]
public async Task Handler_Succeeds_ForResourceOwner() {
    var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("sub", "user1") }));
    var document = new Document { OwnerId = "user1" };
    var requirement = new OwnerRequirement();
    var context = new AuthorizationHandlerContext(new[] { requirement }, user, document);

    await new OwnerAuthorizationHandler().HandleRequirementAsync(context, requirement, document);

    Assert.True(context.HasSucceeded);
}
Real-world example
A test suite for a resource-based OwnerAuthorizationHandler directly verifies both the success case (matching owner) and failure case (non-owner) without needing WebApplicationFactory or a real HTTP request, keeping the tests fast and focused.
Likely follow-ups
  • When would you need a full integration test instead of this isolated handler unit test?
  • How do you test a policy composed of multiple requirements together?
Testing ASP.NET Core Applications Filters
Q12 Intermediate Save

How does the [Authorize] attribute interact with Razor Pages, given they don't use the traditional controller/action model?

Razor Pages support [Authorize] applied directly to the PageModel class, or more commonly, centralized authorization conventions configured via AddRazorPages().AddPageRoute() or AuthorizeFolder()/AuthorizePage() calls in Program.cs, letting you apply authorization requirements to entire folders of pages (like every page under /Admin) without annotating each PageModel individually.
builder.Services.AddRazorPages(options => {
    options.Conventions.AuthorizeFolder("/Admin");  // protects every page under /Pages/Admin
    options.Conventions.AllowAnonymousToPage("/Admin/Login");  // exception within that folder
});
Real-world example
An admin section of a Razor Pages application protects an entire /Admin folder of pages with a single AuthorizeFolder convention call, rather than adding an [Authorize] attribute to every individual PageModel class within that folder.
Likely follow-ups
  • How do folder-level conventions interact with page-level [Authorize] attribute overrides?
  • What's the equivalent pattern for protecting an entire minimal API route group?
Endpoint Metadata Route Constraints & Templates Controllers vs Minimal APIs
Q13 Advanced Save

How would you design an authorization system supporting dynamically-configurable, admin-managed permissions rather than hardcoded policies in code?

Instead of hardcoding every policy's logic in Program.cs, store permission definitions and role-to-permission mappings in a database, then implement a custom IAuthorizationHandler that checks a generic "HasPermission" requirement against the database-driven mapping (often cached for performance) -- letting administrators add, modify, or remove permissions and role assignments through an admin UI without requiring a code deployment for every permission change.
public class PermissionRequirement : IAuthorizationRequirement { public string Permission { get; } public PermissionRequirement(string p) => Permission = p; }

public class PermissionHandler : AuthorizationHandler<PermissionRequirement> {
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) {
        var userId = context.User.FindFirst("sub")?.Value;
        if (await _permissionService.UserHasPermissionAsync(userId, requirement.Permission))
            context.Succeed(requirement);
    }
}
Real-world example
An enterprise SaaS platform lets customer administrators define custom roles with granular permission sets through a self-service admin UI, with the ASP.NET Core authorization system checking against this database-driven permission model rather than a fixed set of code-defined policies.
Likely follow-ups
  • How do you efficiently cache permission lookups to avoid a database call on every authorization check?
  • How does this dynamic model interact with the declarative [Authorize(Policy=...)] attribute syntax?
Configuration & Options Pattern Caching
Q14 Beginner Save

What does IsInRole() check, and how is it related to the [Authorize(Roles = "...")] attribute?

User.IsInRole("Admin") is the imperative, programmatic equivalent of the declarative [Authorize(Roles = "Admin")] attribute -- both check whether the ClaimsPrincipal contains a role claim matching the given value, but IsInRole is used inline within action/endpoint logic when the decision needs to happen conditionally rather than as a blanket endpoint-level restriction.
[HttpGet]
public IActionResult GetReport() {
    if (User.IsInRole("Admin")) {
        return Ok(_fullReport);  // admins see everything
    }
    return Ok(_summaryReport);  // everyone else sees a limited view
}
Real-world example
A reporting endpoint returns a full detailed report for Admin users and a redacted summary for everyone else, using an inline IsInRole check rather than needing two entirely separate endpoints with different [Authorize(Roles=...)] restrictions.
Likely follow-ups
  • When is inline IsInRole preferable to splitting into separate authorized endpoints?
  • How does IsInRole handle a user with multiple roles?
Authorization RESTful Web APIs & Controllers
Q15 Intermediate Save

How do you combine multiple authorization requirements within a single policy, and how are they evaluated (AND vs OR logic)?

By default, all requirements added to a single AuthorizationPolicy must succeed (AND logic) for the policy to pass -- calling RequireClaim, RequireRole, and RequireAssertion multiple times on the same policy builder adds multiple requirements that ALL must be satisfied; achieving OR logic between alternatives requires either a single RequireAssertion with custom OR logic inside it, or defining separate policies checked independently.
builder.Services.AddAuthorization(options => {
    options.AddPolicy("SeniorManager", policy => policy
        .RequireRole("Manager")           // AND
        .RequireClaim("years", "5", "10", "15", "20"));  // must ALSO have 5+ years

    // OR logic requires a single assertion instead:
    options.AddPolicy("ManagerOrAdmin", policy => policy
        .RequireAssertion(ctx => ctx.User.IsInRole("Manager") || ctx.User.IsInRole("Admin")));
});
Real-world example
A policy requiring both a Manager role AND a minimum tenure claim correctly rejects a newly-promoted manager who hasn't yet met the tenure requirement, since both requirements must independently succeed under the default AND evaluation.
Likely follow-ups
  • How would you debug why a policy with multiple requirements unexpectedly fails?
  • What's a cleaner way to express complex OR logic than a single large RequireAssertion?
Authorization Configuration & Options Pattern

Showing 11–15 of 15