0% found this document useful (0 votes)
12 views9 pages

API Security

The document outlines key concepts and practices related to API security, including common threats, strategies for securing APIs, and tools for testing. It also discusses best practices for storing secret keys in C# applications and provides a step-by-step guide for implementing JWT authentication in ASP.NET Core. Additionally, it highlights the importance of automatic JWT validation and the OWASP API Security Top 10 vulnerabilities.

Uploaded by

KVPGANESAN
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views9 pages

API Security

The document outlines key concepts and practices related to API security, including common threats, strategies for securing APIs, and tools for testing. It also discusses best practices for storing secret keys in C# applications and provides a step-by-step guide for implementing JWT authentication in ASP.NET Core. Additionally, it highlights the importance of automatic JWT validation and the OWASP API Security Top 10 vulnerabilities.

Uploaded by

KVPGANESAN
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

API Security – Interview Q&A

1. What is API security and why is it important?


Answer:
API security involves protecting APIs from malicious attacks and misuse. APIs are gateways to
backend services and databases. If not secured, they can be exploited to:
 Leak sensitive data
 Allow unauthorized access
 Cause denial-of-service (DoS)
 Execute code injection attacks

2. What are common threats to APIs?


Answer:
 Injection attacks (SQL, XML, command injection)
 Broken authentication
 Excessive data exposure
 Rate limiting bypass
 Man-in-the-middle (MITM) attacks
 Insufficient logging and monitoring
 Improper asset management

3. What are the main strategies to secure an API?


Answer:
 Authentication and Authorization (e.g., OAuth2.0, JWT)
 Input validation and sanitization
 Rate limiting and throttling
 TLS/SSL encryption
 Use of API gateways
 CORS configuration
 Logging and monitoring
 IP whitelisting / firewall rules

4. What is the difference between authentication and authorization in API security?


Answer:
 Authentication: Confirms the user's identity (e.g., login).
 Authorization: Grants or denies access to resources based on permissions (e.g., admin vs.
user).
✅ AuthN = Who are you?
✅ AuthZ = What can you do?

5. What is OAuth 2.0 and how is it used in APIs?


Answer:
OAuth 2.0 is an authorization framework that lets applications access resources on behalf of a user
without exposing user credentials.
Flow:
User → App → Auth Server → Access Token → Resource Server
Used for:
 Third-party access (Google login)
 Scoped permissions
 Expirable tokens
6. What is JWT and how does it work?
Answer:
JWT (JSON Web Token) is a compact, URL-safe token used for stateless authentication.
Structure:
[Link]
Used to:
 Store claims (user ID, role)
 Prove identity without hitting the DB
 Authenticate subsequent API calls
Verify signature to ensure integrity and authenticity.

7. How do you protect an API from brute force or DoS attacks?


Answer:
 Rate limiting (e.g., 100 requests/minute per IP)
 Throttling
 WAF (Web Application Firewall)
 API gateway enforcement
 Account lockouts after failed logins

8. What is an API gateway and how does it help in security?


Answer:
An API Gateway sits between clients and services. It acts as a reverse proxy, handling:
 Authentication/authorization
 Request/response validation
 Rate limiting
 Logging and monitoring
 SSL termination
Examples: Kong, AWS API Gateway, Apigee, NGINX

9. What is CORS and how does it impact API security?


Answer:
CORS (Cross-Origin Resource Sharing) controls access to APIs from different domains.
Used to:
 Prevent unauthorized cross-origin requests
 Whitelist trusted domains
 Secure public APIs
Misconfigured CORS can leak data to malicious websites.

10. How can you secure sensitive data in API communication?


Answer:
 Use HTTPS (TLS) to encrypt data in transit
 Tokenize or encrypt sensitive fields (e.g., credit card)
 Mask or redact sensitive data in logs
 Avoid sending sensitive data in URLs (use headers/body instead)

11. What is HMAC and how is it used in APIs?


Answer:
HMAC (Hash-based Message Authentication Code) uses a secret key + hash to sign requests.
Used to:
 Validate request authenticity
 Prevent tampering
Common in API key + secret-based authentication systems.

12. What is the OWASP API Security Top 10?


Answer:
A list of top vulnerabilities in APIs as identified by OWASP. Includes:
1. Broken Object Level Authorization
2. Broken Authentication
3. Excessive Data Exposure
4. Lack of Resources & Rate Limiting
5. Broken Function Level Authorization
6. Mass Assignment
7. Security Misconfiguration
8. Injection
9. Improper Assets Management
10. Insufficient Logging & Monitoring

13. How do you validate user input in an API?


Answer:
 Use whitelisting over blacklisting
 Sanitize inputs to prevent injection attacks
 Use frameworks like Joi ([Link]), FluentValidation (.NET), etc.
 Apply schema validation for JSON/XML

14. Can you explain mutual TLS (mTLS)?


Answer:
mTLS is two-way SSL: both client and server present certificates.
Used to:
 Authenticate both parties
 Prevent unauthorized clients from connecting
Common in B2B APIs and microservices communication.

15. How would you log and monitor API security events?
Answer:
 Log all failed/successful authentication attempts
 Use tools like ELK Stack, Splunk, or CloudWatch
 Monitor for anomalies (e.g., spikes, geo-locations)
 Set up alerts for suspicious activity

⚙️BONUS: Tools for API Security Testing


 Postman (with security headers)
 OWASP ZAP
 Burp Suite
 Insomnia
 Fiddler
 API security scanners like 42Crunch, Snyk, etc.

Storing Secret Keys in C# Applications

✅ 1. Environment Variables (Recommended for Production)


How to Set (OS-level):
 Windows (CMD):
 setx API_KEY "your-secret-key"
 Linux/macOS (Bash):
 export API_KEY="your-secret-key"
Access in C#:
string apiKey = [Link]("API_KEY");

✅ 2. User Secrets (for local development – .NET Core / [Link] Core)


Use the built-in User Secrets feature (safe and encrypted locally).
Step 1: Initialize user secrets in your project:
dotnet user-secrets init
Step 2: Add a secret:
dotnet user-secrets set "ApiKeys:MySecret" "your-secret-key"
Step 3: Read it from [Link] or code:
In [Link] or [Link]:
[Link]<Program>();
In code:
string secret = [Link]["ApiKeys:MySecret"];
📁 Secrets are stored in:
%APPDATA%\Microsoft\UserSecrets\{GUID}\[Link]

✅ 3. Azure Key Vault (Recommended for Cloud)


Use Azure Key Vault to store secrets and fetch them securely.
Install NuGet Packages:
dotnet add package [Link]
dotnet add package [Link]
Access secrets:
using [Link];
using [Link];

var client = new SecretClient(


new Uri("[Link]
new DefaultAzureCredential());

KeyVaultSecret secret = await [Link]("MySecretKey");


string secretValue = [Link];

✅ 4. [Link] (Not Recommended for Secrets)


If you must store something in [Link], do not commit real secrets.
[Link]
{
"ApiKeys": {
"MySecret": "your-secret-key"
}
}
Access in C#:
string secret = [Link]["ApiKeys:MySecret"];
🛑 Make sure to use different configs for production and exclude secrets from version control.

❌ Bad Practice: Hardcoding Secrets in Code


// ❌ Don't do this
string apiKey = "my-hardcoded-secret";
This is dangerous because:
 It can leak via GitHub
 Difficult to rotate or manage
 Easy to decompile from binaries

🔐 Summary: Where to Store Secrets in C# Projects


Method Environment Use Case Secure?
Environment Variables Dev / Prod Config in containers, cloud ✅ Good
User Secrets Dev only (local) Local development secrets ✅ Good
Azure Key Vault Production cloud Enterprise-grade security ✅ Best
[Link] Dev/Test only Non-sensitive config only ⚠️Ok
Hardcoded in code Never Avoid completely ❌ Bad

Got it! Let’s go step by step on how to use JWT for a REST API in [Link] Core, from generation to
validation.

1. Install Required Packages


Install-Package [Link]
Install-Package [Link]

2. Generate JWT Token (Server Side)


Create a method to issue JWT when a user logs in:
using [Link];
using [Link];
using [Link];
using [Link];

public string GenerateJwtToken(string userId, string userName)


{
var secretKey = new SymmetricSecurityKey([Link]("YOUR_SECRET_KEY"));
var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

var claims = new[]


{
new Claim([Link], userId),
new Claim([Link], userName),
new Claim([Link], [Link]().ToString())
};

var token = new JwtSecurityToken(


issuer: "MyApp",
audience: "MyAppClient",
claims: claims,
expires: [Link](30),
signingCredentials: signingCredentials
);

return new JwtSecurityTokenHandler().WriteToken(token);


}
 This generates a signed JWT with claims and expiry.
3. Configure JWT Validation in REST API
In [Link]:
using [Link];
using [Link];
using [Link];

var builder = [Link](args);


var key = [Link]("YOUR_SECRET_KEY");

[Link]([Link])
.AddJwtBearer(options =>
{
[Link] = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = "MyApp",
ValidateAudience = true,
ValidAudience = "MyAppClient",
ValidateLifetime = true,
ClockSkew = [Link]
};
});

[Link]();

var app = [Link]();

[Link](); // JWT validation middleware


[Link]();

[Link]();
[Link]();

4. Protect API Endpoints


using [Link];
using [Link];

[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase
{
[HttpGet("profile")]
[Authorize] // Only valid JWT can access
public IActionResult GetProfile()
{
var userId = [Link]([Link])?.Value;
var userName = [Link]([Link])?.Value;
return Ok(new { Id = userId, Name = userName });
}
}
 Any request without a valid JWT will get 401 Unauthorized.

5. Client Sends JWT


In REST API calls, client includes JWT in header:
GET /api/user/profile
Authorization: Bearer <JWT_TOKEN>
 Server middleware automatically validates the token before executing the controller.

6. Optional: Refresh Tokens


 For longer sessions, issue short-lived access tokens (JWT) and a long-lived refresh token.
 Store refresh token securely on server or HTTP-only cookie.
 When JWT expires, client requests a new JWT using the refresh token.

✅ Summary for REST API


1. Client logs in → server generates JWT.
2. Client stores JWT securely (LocalStorage or HTTP-only cookie).
3. Client sends JWT in Authorization: Bearer <token> header for every API call.
4. [Link] Core JWT middleware validates token automatically.
5. Server processes request only if token is valid.

You don’t have to write manual code to verify JWT tokens in most cases — modern frameworks like
[Link] Core provide automatic JWT validation via middleware. Let me explain the two approaches:

1. Automatic JWT Validation (Recommended)


[Link] Core has built-in support using [Link].
Example in [Link]
using [Link];
using [Link];
using [Link];

var builder = [Link](args);


var key = [Link]("YOUR_SECRET_KEY");

[Link](options =>
{
[Link] = [Link];
[Link] = [Link];
})
.AddJwtBearer(options =>
{
[Link] = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = "MyApp",
ValidateAudience = true,
ValidAudience = "MyAppClient",
ValidateLifetime = true,
ClockSkew = [Link]
};
});

[Link]();

var app = [Link]();

[Link](); // middleware automatically validates JWT


[Link]();

[Link]();

[Link]();
✅ After this setup:
 Any controller/action with [Authorize] automatically validates the token.
 If the token is invalid, expired, or tampered with → returns 401 Unauthorized.
 You don’t need to manually decode or verify the signature.

2. Manual Validation (Optional / Low-Level)


Sometimes, you might want to validate a JWT manually, for example:
using [Link];
using [Link];
using [Link];

var tokenHandler = new JwtSecurityTokenHandler();


var key = [Link]("YOUR_SECRET_KEY");

try
{
[Link](token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidIssuer = "MyApp",
ValidateAudience = true,
ValidAudience = "MyAppClient",
ValidateLifetime = true
}, out SecurityToken validatedToken);

// Token is valid
}
catch
{
// Token is invalid or expired
}
✅ This gives full control but usually unnecessary in standard [Link] Core apps.
3. Recommendation
 Use automatic JWT validation via AddJwtBearer() middleware.
 Manual validation is only needed if you have custom token handling or non-standard
requirement

You might also like