Mid MVC

Now, only requests with a valid JWT in the Authorization: Bearer <token> header can access it. 󰰣 6. Explain role-based authorization.?

Role-based authorization restricts access based on user roles.

Assign a role:

await _userManager.AddToRoleAsync(user, "Admin");

Use in controllers:

[Authorize(Roles = "Admin")]

public IActionResult Dashboard() => View();

You can also combine roles:

[Authorize(Roles = "Admin,Manager")]

🧭 7. What is policy-based authorization?

Policy-based authorization gives fine-grained control over access using custom rules.

Instead of just roles, you define policies with specific requirements.

Define a policy:

builder.Services.AddAuthorization(options =>

options.AddPolicy("RequireAdminEmail", policy =>

Follow :

policy.RequireClaim(ClaimTypes.Email, "admin@myapp.com"));

});

Apply policy:

[Authorize(Policy = "RequireAdminEmail")]

public IActionResult AdminOnly() => View();

⚖ 8. How to create custom authorization policies?

You can write custom authorization handlers to evaluate complex logic.

Example:

public class MinimumAgeRequirement : IAuthorizationRequirement

public int Age { get; }

public MinimumAgeRequirement(int age) => Age = age;

public class MinimumAgeHandler :

AuthorizationHandler<MinimumAgeRequirement>

protected override Task HandleRequirementAsync(

AuthorizationHandlerContext context, MinimumAgeRequirement

requirement)

var birthDateClaim = context.User.FindFirst(c => c.Type ==

"BirthDate");

if (birthDateClaim != null)

var birthDate = DateTime.Parse(birthDateClaim.Value);

if (birthDate.AddYears(requirement.Age) <=

DateTime.Today)

context.Succeed(requirement);

Follow :

return Task.CompletedTask;

Register it:

builder.Services.AddAuthorization(options =>

options.AddPolicy("AdultOnly", policy =>

policy.Requirements.Add(new MinimumAgeRequirement(18)));

});

builder.Services.AddSingleton<IAuthorizationHandler,

MinimumAgeHandler>();

Use it:

[Authorize(Policy = "AdultOnly")]

public IActionResult BuyAlcohol() => Ok("Access granted");

🍪 9. What is cookie authentication in ASP.NET Core?

Cookie authentication stores user information in an encrypted cookie on the browser.

When the user revisits, the cookie is used to identify them.

Configure:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.Auth

enticationScheme)

.AddCookie(options =>

options.LoginPath = "/Account/Login";

options.ExpireTimeSpan = TimeSpan.FromMinutes(30);

});

Once the user logs in:

Follow :

await HttpContext.SignInAsync(

CookieAuthenticationDefaults.AuthenticationScheme,

new ClaimsPrincipal(identity));

🌐 10. How to integrate OAuth2 / OpenID Connect in

ASP.NET Core?

ASP.NET Core supports external providers like Google, Microsoft, Azure AD, etc. using

OAuth2 and OpenID Connect.

Example for OpenID Connect (Azure AD):

builder.Services.AddAuthentication(OpenIdConnectDefaults.Authenticat

ionScheme)

.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureA

d"));

appsettings.json:

"AzureAd": {

"ClientId": "your-client-id",

"TenantId": "your-tenant-id",

"Instance": "

"CallbackPath": "/signin-oidc"

This handles sign-in, token validation, and claims setup automatically.

🔐 11. How to implement Google or Azure AD login?

builder.Services.AddAuthentication()

Follow :

.AddGoogle(options =>

options.ClientId = builder.Configuration["Google:ClientId"];

options.ClientSecret =

builder.Configuration["Google:ClientSecret"];

});

For Azure AD:

builder.Services.AddAuthentication(OpenIdConnectDefaults.Authenticat

ionScheme)

.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureA

d"));

ASP.NET Core will redirect users to Google/Azure login and handle tokens automatically.

🧱 12. What is AuthorizeAttribute?

[Authorize] is an attribute that restricts access to actions or controllers.

Examples:

[Authorize] // Any logged-in user

[Authorize(Roles = "Admin")] // Only admins

[Authorize(Policy = "AdultOnly")] // Custom policy

You can also allow anonymous access:

[AllowAnonymous]

public IActionResult Login() => View();

🧭 13. How to protect specific actions or controllers?

Follow :

Apply [Authorize] at different levels:

Controller-level:

[Authorize]

public class OrdersController : Controller { ... }

Action-level:

[Authorize(Roles = "Manager")]

public IActionResult ApproveOrder() => View();

⚙ 14. What are authentication schemes?

An authentication scheme defines how users are authenticated — via cookies, JWT,

Google, etc.

Each scheme has:

  • A name
  • A handler (e.g., JWT handler, cookie handler)

Example:

builder.Services.AddAuthentication()

.AddCookie("Cookies")

.AddJwtBearer("Jwt", options => { ... });

You can specify the scheme explicitly:

[Authorize(AuthenticationSchemes = "Jwt")]

🔄 15. How to use multiple authentication handlers?

Follow :

You can configure multiple schemes and choose dynamically per endpoint.

Example:

builder.Services.AddAuthentication(options =>

options.DefaultAuthenticateScheme = "JwtOrCookie";

.AddPolicyScheme("JwtOrCookie", "JWT or Cookie", options =>

options.ForwardDefaultSelector = context =>

context.Request.Headers.ContainsKey("Authorization") ? "Jwt"

: "Cookies";

.AddCookie("Cookies")

.AddJwtBearer("Jwt", options => { ... });

This setup allows both cookie-based (web) and JWT (API) authentication in the same app.

✅ Summary:

  • ASP.NET Core Identity manages users and roles.
  • Claims-based authentication represents user info flexibly.
  • JWT enables stateless API security.
  • Policies allow custom rules beyond roles.
  • Schemes let you combine multiple authentication systems (cookies, JWT, Google).

Configuration & Environments

More from ASP.NET Core MVC Tutorial

All questions for this course