Securing Your API

Advanced 30 min read Lesson 10 of 10
The VIP Club Story: Your API is a VIP club. You don't want just anyone walking in! You need a bouncer at the door. In ASP.NET Core, the bouncer is the [Authorize] attribute, and the VIP pass is the user's Token.

Connecting to C#

If you have a C# method that deletes a user, you want to ensure only an Admin can call it. You don't write if (user.IsAdmin) inside the method. Instead, you let the framework handle security before the method is even executed.

Authentication vs Authorization

  • Authentication (AuthN): "Who are you?" (Logging in).
  • Authorization (AuthZ): "Are you allowed to do this?" (Checking permissions).

Example 1: The Bouncer ([Authorize])

By adding the [Authorize] attribute to your Controller, you block all unauthenticated users from accessing it.

[Authorize] // <--- The Bouncer
[ApiController]
[Route("api/[controller]")]
public class SecretController : ControllerBase
{
    [HttpGet("admin-data")]
    public IActionResult GetSecretData()
    {
        // Only logged-in users can see this
        return Ok("This is top secret data!");
    }
}

Example 2: API Keys (A simple approach)

Sometimes you just want to give a password to another developer so their app can talk to yours. You check for an "X-API-KEY" in the request headers.

[HttpGet]
public IActionResult GetData([FromHeader(Name = "X-API-KEY")] string apiKey)
{
    if (apiKey != "my-super-secret-key-123")
    {
        return Unauthorized("Invalid API Key!"); // Returns 401
    }

    return Ok("Welcome to the API!");
}
Mastery Achieved!

You now understand APIs from top to bottom. You know how they work, how to build them with C#, how to secure them, and how to talk to them. Go build something amazing!

Test Your Knowledge - Take Quiz