Skip to main content

πŸš€ 30 Tricky Interview Questions on Authentication & Authorization in .NET Core Web API – With Detailed Answers πŸ’‘

 Are you preparing for a .NET Core interview or looking to master secure Web API development? Here's your go-to guide with 30 advanced Authentication & Authorization questions, perfect for cracking interviews or leveling up your skills. ✅

πŸ” Authentication vs Authorization

  1. What is the difference between Authentication and Authorization?

    • Authentication verifies who you are.

    • Authorization defines what you can access.

    • Example: Logging in = Authentication; Viewing dashboard = Authorization.


πŸ”‘ JWT Token-Based Authentication

  1. What is JWT and why is it used in Web API?

    • JWT (JSON Web Token) is a compact, URL-safe token used to transfer claims between two parties. It’s widely used for stateless authentication.

  2. How do you generate JWT in .NET Core?

    • Use System.IdentityModel.Tokens.Jwt.

    • Configure TokenValidationParameters and generate token using JwtSecurityTokenHandler.

  3. What are claims in JWT?

    • Claims are key-value pairs that represent user identity (e.g., Name, Email, Role).

  4. What is the purpose of the 'Issuer' and 'Audience' in JWT?

    • Issuer: Who created the token.

    • Audience: Who the token is intended for.


🧩 Role-Based Authorization

  1. How is role-based authorization implemented in .NET Core?

    • Decorate actions or controllers using [Authorize(Roles = "Admin")].

  2. Can a user have multiple roles in JWT?

    • Yes. Use multiple "role" claims or an array of roles in the JWT payload.

  3. How do you secure endpoints for multiple roles?

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

πŸ›‘️ Policy-Based Authorization

  1. What is policy-based authorization?

    • Instead of static roles, policies allow custom logic via requirements and handlers.

  2. How do you define a custom policy?

  • Use services.AddAuthorization(options => {...}) and register requirements.

  1. How do you implement a custom AuthorizationHandler?

  • Inherit from AuthorizationHandler<TRequirement> and override HandleRequirementAsync.


πŸ”ƒ Token Refresh & Expiry

  1. What happens when a JWT token expires?

  • The client gets a 401 Unauthorized. You can implement a refresh token strategy.

  1. How do you implement Refresh Tokens?

  • Store refresh tokens server-side. On expiry, send a new access token using the refresh token.


πŸ”„ OAuth2 & OpenID Connect

  1. What is the difference between OAuth2 and OpenID Connect?

  • OAuth2 is for authorization.

  • OpenID Connect is built on OAuth2 and adds authentication features.

  1. How to implement Google/Facebook login in .NET Core?

  • Use AddAuthentication().AddGoogle() or AddFacebook() in Startup.cs.


πŸ” IdentityServer & External Providers

  1. What is IdentityServer?

  • A powerful framework for implementing OAuth2 and OpenID Connect in .NET Core.

  1. How do you secure an API using IdentityServer4?

  • Configure IdentityServer, generate tokens, and validate them in the Web API using middleware.


πŸ“¦ ASP.NET Core Identity

  1. What is ASP.NET Core Identity?

  • A full-featured membership system for managing users, passwords, roles, and claims.

  1. How do you override password rules in Identity?

  • Configure PasswordOptions in IdentityOptions during service configuration.


πŸ“Œ Middleware & Token Validation

  1. Where should you validate JWT tokens in the middleware pipeline?

  • After UseRouting() but before UseEndpoints().

  1. How can you access the currently logged-in user?

  • Use HttpContext.User.Identity.Name or access claims from User.Claims.


🚧 Advanced & Tricky Scenarios

  1. Can you invalidate a JWT token before it expires?

  • JWTs are stateless, so you must implement token revocation via a server-side blacklist.

  1. How to prevent token replay attacks?

  • Use short-lived tokens with refresh strategy, and track usage on the server.

  1. Is HTTPS required for JWT?

  • Yes. JWTs contain sensitive info and must be transmitted over HTTPS.

  1. How to secure Swagger endpoints?

  • Use [Authorize] on controllers and configure Swagger to accept Bearer tokens.

  1. What’s the risk of putting roles in the JWT?

  • If the token is compromised, all role info is exposed. Always encrypt tokens and use HTTPS.


πŸ” Multi-Tenancy & Claims

  1. How to implement multi-tenancy authorization?

  • Include tenant info in claims and validate it in custom handlers or filters.

  1. How do you manage per-tenant roles?

  • Use custom claims like TenantId and role mapping logic based on tenant.


⚙️ Miscellaneous

  1. Difference between [Authorize], [AllowAnonymous], and [Authorize(Roles = "...")]?

  • [Authorize]: Requires authentication.

  • [AllowAnonymous]: Skips auth.

  • [Authorize(Roles = "...")]: Requires specific role.

  1. How to log authorization failures?

  • Hook into OnChallenge or OnForbidden events in JWT bearer options.


πŸ‘¨‍πŸ’» Bonus Tips

  • Always secure APIs using HTTPS.

  • Rotate keys and secrets regularly.

  • Prefer short-lived tokens with refresh strategy.

  • Validate tokens strictly (issuer, audience, lifetime, signing key).


πŸ’¬ Let me know in the comments which question was most helpful!
πŸ‘ Like & πŸ” Repost to help others ace their .NET Core interviews!

Comments

Popular posts from this blog

Top 30 Tricky C# Coding Interview Questions (With Solutions)

  1. Reverse a String Without Built-in Methods Q: Write a C# method to reverse a string without using built-in reverse functions. A: string Reverse(string input) {     char[] result = new char[input.Length];     for (int i = 0; i < input.Length; i++)         result[i] = input[input.Length - 1 - i];     return new string(result); } 2. Find Duplicates in an Integer Array Q: Detect and print duplicates in an integer array. A: void FindDuplicates(int[] arr) {     var seen = new HashSet<int>();     foreach (int num in arr) {         if (seen.Contains(num))             Console.WriteLine("Duplicate: " + num);         else             seen.Add(num);   ...

Ace Your .NET Core Coding Interview: Top 20 Algorithmic & Problem-Solving Questions

 Beyond knowing the ins and outs of .NET Core, a successful technical interview often hinges on your ability to solve fundamental coding problems. These questions test your logical thinking, algorithm design, and grasp of basic data structures. This blog post provides 20 essential coding interview questions, complete with explanations and example approaches in C#, to help you shine in your next .NET Core technical assessment. 1. Reverse a String Without Built-in Functions Explanation: A classic that tests your understanding of loops and string manipulation. Question: Write a C# method to reverse a given string without using built-in Reverse() or ToArray() methods. Answer: C# public string ReverseString ( string input ) { if ( string .IsNullOrEmpty(input)) { return input; } char [] charArray = input.ToCharArray(); int left = 0 ; int right = charArray.Length - 1 ; while (left < right) { // Swap characters char...

Cracking the Code: Your Guide to the Top 60 C# Interview Questions

So, you're gearing up for a C# interview? Fantastic! This powerful and versatile language is a cornerstone of modern software development, and landing that C# role can open up a world of exciting opportunities. But navigating the interview process can feel like traversing a complex codebase. Fear not! We've compiled a comprehensive list of the top 60 C# interview questions, complete with detailed answers, to help you ace your next technical challenge. Whether you're just starting your C# journey or you're a seasoned pro looking to brush up your knowledge, this guide has something for you. We've broken down the questions into three levels: Beginner, Intermediate, and Advanced, allowing you to focus on the areas most relevant to your experience. Let's dive in and equip you with the knowledge you need to shine! Beginner Level (1–20) 1. What is C#? C# is a modern, object-oriented programming language developed by Microsoft as part of its .NET platform. It is design...