Skip to main content

Junior ASP.NET Web API Interview Questions

Curated Junior-level ASP.NET Web API interview questions for developers targeting junior positions. 20 questions available.

Last updated:

ASP.NET Web API Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of ASP.NET Web API interview questions and answers. This page contains expertly curated interview questions covering all aspects of ASP.NET Web API, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our ASP.NET Web API interview questions are designed to help you:

  • Understand core concepts and best practices in ASP.NET Web API
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next ASP.NET Web API interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic ASP.NET Web API concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

20 questions
Q1:

How do you implement authentication in Web API?

Junior

Answer

Authentication verifies user identity in Web API.

Common implementations:

  • JWT Bearer Tokens – stateless authentication for SPA and mobile apps.
  • OAuth2 / OpenID Connect – external identity providers.
  • Cookie authentication – mainly for browser-based apps.

Configured using AddAuthentication() and UseAuthentication().

Quick Summary: JWT authentication: client sends Authorization: Bearer header. AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer() validates the JWT signature, issuer, audience, and expiration. Claims from the token populate HttpContext.User. Apply [Authorize] to require authentication. Use [Authorize(Roles = "Admin")] for role-based access. Always use HTTPS to protect tokens in transit.
Q2:

How does JWT authentication work?

Junior

Answer

JWT workflow:

  • User logs in ? server generates a signed JWT.
  • Client sends token in Authorization: Bearer <token>.
  • Server validates signature and extracts claims.
  • No server-side session required.
Quick Summary: JWT workflow: client authenticates (username/password) and receives a signed JWT from the auth server. JWT contains claims (user ID, roles, expiry) in a Base64-encoded payload. The server signs with a secret/private key. On subsequent requests, client sends the JWT. Server validates signature and expiry without hitting the database. Short-lived access tokens (15 min) + refresh tokens for renewal.
Q3:

How do you implement role-based authorization?

Junior

Answer

Use role-based authorization with:

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

Roles are validated from claims inside the JWT or identity provider.

Quick Summary: Role-based authorization: add roles as claims in the JWT or use ASP.NET Core Identity roles. [Authorize(Roles = "Admin,Manager")] restricts to users with those roles. Multiple roles in one attribute = OR logic. Stack multiple [Authorize] attributes for AND logic. Check roles in code: User.IsInRole("Admin"). Roles are a simple but coarse-grained authorization mechanism.
Q4:

What is claims-based authorization?

Junior

Answer

Claims-based authorization checks user claims instead of static roles.

Implemented using policy-based authorization:

services.AddAuthorization(options =>
{
    options.AddPolicy("HRPolicy",
        policy => policy.RequireClaim("Department", "HR"));
});
Quick Summary: Claims-based authorization: JWT/Identity tokens carry claims (key-value pairs about the user). [Authorize(Policy = "MinimumAge")] uses a policy that evaluates claims. Define policies: builder.Services.AddAuthorization(opts => opts.AddPolicy("MinimumAge", p => p.RequireClaim("age"))). More flexible than roles - claims can carry any attribute (department, subscription level, specific permissions).
Q5:

How do you create custom authorization policies?

Junior

Answer

Create policies in Program.cs using AddAuthorization.

Apply using [Authorize(Policy="PolicyName")].

Useful for domain-specific access control.

Quick Summary: Custom authorization policies: AddPolicy("CanEdit", policy => policy.Requirements.Add(new CanEditRequirement())). Implement IAuthorizationHandler: check the requirement against user claims and resource. Register handler with DI. Apply with [Authorize(Policy = "CanEdit")]. Resource-based authorization: pass the resource to IAuthorizationService.AuthorizeAsync(User, resource, "CanEdit").
Q6:

What is the difference between authentication and authorization?

Junior

Answer

Authentication: Verifies user identity.

Authorization: Determines what the authenticated user can access.

Quick Summary: Authentication: verifies who the user is (reads JWT/cookie, validates signature, extracts claims into HttpContext.User). Must happen before authorization. Authorization: decides what the authenticated user can do (reads claims, evaluates policies, checks [Authorize] attributes). These are separate concerns and separate middleware. A user can be authenticated (valid token) but not authorized (wrong role).
Q7:

How do you secure sensitive API endpoints?

Junior

Answer

Secure endpoints using:

  • [Authorize] attribute
  • HTTPS enforcement
  • Input validation
  • Rate limiting
  • CORS restrictions
Quick Summary: Secure sensitive endpoints: require authentication ([Authorize]), enforce HTTPS, apply role/policy authorization, rate limit login and sensitive operations, log all access attempts (with user ID and IP), validate all inputs, use parameterized queries for DB access, and return minimal error details. For extra-sensitive data: add IP allowlisting, require MFA, and audit every access.
Q8:

How do you handle token expiration in JWT?

Junior

Answer

JWT includes an exp claim for expiration.

API rejects expired tokens automatically.

Refresh tokens extend the session securely.

Quick Summary: JWT expiration handling: issue short-lived access tokens (15-60 min) and longer-lived refresh tokens. When access token expires, client uses refresh token to get a new access token from the auth endpoint. Validate refresh tokens against a store (Redis/DB) to allow revocation. Rotate refresh tokens on use (detect replay attacks). Use sliding expiration: refresh token TTL resets on each use.
Q9:

How do you protect against CSRF attacks in APIs?

Junior

Answer

API best practices:

  • Use JWT instead of cookies
  • Enable strict CORS policies
  • Use anti-forgery tokens if cookies are used
Quick Summary: CSRF attacks trick authenticated users into making unwanted requests. For stateless JWT APIs (Authorization header): CSRF is not a concern (browsers don't auto-send custom headers). For cookie-based auth: use antiforgery tokens (ValidateAntiforgeryToken), SameSite=Strict/Lax cookie attribute, or custom request header validation. Most REST APIs using Bearer tokens don't need CSRF protection.
Q10:

How do you secure API keys in Web API?

Junior

Answer

Best practices:

  • Store in Key Vault or environment variables
  • Never hard-code keys
  • Rotate keys periodically
Quick Summary: Secure API keys: store in environment variables or Azure Key Vault (never in code or config files). Pass as Authorization header or custom header (not in URL - it gets logged). Hash and store API keys server-side (don't store plaintext). Rotate keys regularly. Scope keys to minimum required permissions. Rate limit per API key. Log all API key usage for auditing.
Q11:

What is OAuth2 and how is it used with Web API?

Junior

Answer

OAuth2 is a secure authorization framework.

Flow: Client ? Auth Server ? Access Token ? API.

Supports scopes, roles, and claims.

Quick Summary: OAuth2 is an authorization framework. Web API acts as a Resource Server that accepts OAuth2 access tokens. An Authorization Server (IdentityServer, Azure AD, Auth0) issues tokens. Clients get tokens by presenting credentials (client credentials flow for machine-to-machine, authorization code flow for users). The API validates tokens using the auth server's public keys (JWKS endpoint).
Q12:

How do scopes differ from roles in OAuth2?

Junior

Answer

Roles: Broad user categories.

Scopes: Fine-grained permissions such as read:orders.

Quick Summary: Roles: coarse-grained groups (Admin, User, Manager) assigned to users. Scopes in OAuth2: specific permissions requested by a client app for what it can do with the API (read:orders, write:products). Roles are about who the user is. Scopes are about what the client application is allowed to do. An API might check both: user must have Admin role AND client must have write scope.
Q13:

How do you implement token revocation?

Junior

Answer

Token revocation strategies:

  • Blacklist tokens in database
  • Short-lived access tokens
  • Rotating refresh tokens
Quick Summary: Token revocation: JWTs are stateless - no built-in revocation. To revoke: maintain a token blocklist in Redis (check on each request, fast lookup). Short-lived tokens reduce the window. Use refresh token rotation - invalidate refresh token on use or logout. For immediate revocation (compromised account): store user's "token issued before" timestamp and reject tokens issued before logout.
Q14:

How do you implement multi-tenant security?

Junior

Answer

Multi-tenant API security includes:

  • Tenant ID in claims or headers
  • Middleware-based access validation
  • Database filtering by tenant context
Quick Summary: Multi-tenant security: include tenant ID in JWT claims. Validate tenant claim on every request. Filter all DB queries by tenant ID (row-level security or query filters in EF Core). Use separate schemas or databases per tenant for stronger isolation. Prevent tenant data leakage in error messages. Audit cross-tenant access attempts. Use EF Core global query filters to automatically apply tenant filtering.
Q15:

How do you prevent over-posting attacks?

Junior

Answer

Use DTOs instead of binding directly to entity models.

Expose only allowed fields.

Always validate incoming payloads.

Quick Summary: Over-posting: client sends extra fields that get bound to the model and saved unintentionally (e.g., sending IsAdmin=true and having it bound to the user object). Prevent with: separate DTOs for input (only include fields clients should set), [BindNever] to exclude properties, or explicit model mapping. Never bind domain entities directly to HTTP request bodies in production APIs.
Q16:

What are best practices for securing Web API endpoints?

Junior

Answer

  • Force HTTPS
  • Use [Authorize]
  • Limit payload size
  • Use secure headers
  • Validate all inputs
  • Implement logging & monitoring
Quick Summary: Web API security best practices: always use HTTPS, authenticate every endpoint ([Authorize]), validate all inputs, use parameterized queries for DB access, return minimal error details (no stack traces), implement rate limiting, keep dependencies updated, scan for vulnerabilities (Snyk, OWASP), log security events (failed auth, suspicious requests), and apply CORS restrictions to trusted origins only.
Q17:

How do you implement refresh tokens securely?

Junior

Answer

Best practices:

  • Store refresh tokens securely
  • Use rotating refresh tokens
  • Issue short-lived access tokens
  • Revoke tokens on suspicious activity
Quick Summary: Refresh tokens securely: store server-side as hashed values (never plaintext) in DB/Redis. Issue new access token + new refresh token on each refresh (rotation). Invalidate old refresh token after rotation. Detect reuse: if a rotated token is presented again, revoke all tokens for that user (indicates theft). Set refresh token expiry (7-30 days). Store in HttpOnly cookie or secure storage (not localStorage).
Q18:

How do you check roles and claims programmatically?

Junior

Answer

Use HttpContext methods:

  • User.IsInRole("Admin")
  • User.Claims to inspect claim values
Quick Summary: Check roles and claims in code: User.IsInRole("Admin"), User.HasClaim(c => c.Type == "dept" && c.Value == "Engineering"), User.FindFirst(ClaimTypes.Email)?.Value. In controllers with [Authorize] applied, HttpContext.User is always populated with the authenticated user's claims. Use IAuthorizationService.AuthorizeAsync() for resource-based checks where the specific resource matters.
Q19:

How do you implement custom JWT claims?

Junior

Answer

Add claims during token creation (email, role, custom fields).

Validate claims in controllers or authorization policies.

Quick Summary: Custom JWT claims: add claims when generating the token: new Claim("subscription", "premium"), new Claim("tenant_id", tenantId). Read in controllers: User.FindFirst("subscription")?.Value. Map custom claims to a strongly-typed object with custom IClaimsTransformation. Use claim names consistently with reverse-DNS format (com.company.claim-name) to avoid conflicts with standard claim names.
Q20:

How do you audit API usage for security?

Junior

Answer

Audit using structured logs including:

  • User identity
  • Action invoked
  • Timestamp
  • IP address
  • Request and response metadata

Essential for compliance and threat detection.

Quick Summary: Audit API usage: log every authenticated request with user ID, endpoint, timestamp, source IP, and response status. Use structured logging (Serilog/NLog) to a searchable log store. Action filters or middleware for consistent audit logging across all endpoints. Flag anomalous patterns (many requests in short time, unusual endpoints). Retain audit logs per compliance requirements (GDPR, PCI-DSS).

Curated Sets for ASP.NET Web API

No curated sets yet. Group questions into collections from the admin panel to feature them here.

Ready to level up? Start Practice