Skip to main content

Simplifying Azure Web API Authentication with C# Code Examples

 Simplifying Azure Web API Authentication with C# Code Examples

Authentication is a crucial aspect of securing your web APIs, ensuring that only authorized users or applications can access your resources. Azure offers various authentication methods to protect your web API and verify the identity of incoming requests. In this article, we'll explore some common Azure authentication methods and provide simplified C# code examples to illustrate their implementation.


Azure Active Directory (Azure AD) Authentication

Azure AD is Microsoft's identity and access management service. It enables you to authenticate users and applications, manage their access, and secure your web APIs. Here's a simple C# code snippet to demonstrate Azure AD authentication for your API:

public async Task<IActionResult> SecureApi()
{
    // Use Azure AD authentication middleware to secure the API
    if (User.Identity.IsAuthenticated)
    {
        // Authorized access
        return Ok("Authenticated user.");
    }
    else
    {
        // Unauthorized access
        return Unauthorized();
    }
}

With Azure AD, you can also configure role-based access control (RBAC) to define who can do what in your API.

API Key Authentication

API key authentication involves providing clients with a secret token (API key) that they include in their requests. While simple, it has limitations in terms of security. Here's a straightforward C# code snippet to illustrate API key authentication:

 In this example, we'll use the Microsoft.AspNetCore.Authorization library to create a custom authorization attribute for API key validation.

Here's a simplified example:

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ApiKeyAttribute : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // Get the API key from the request headers
        if (!context.HttpContext.Request.Headers.TryGetValue("Api-Key", out var apiKey))
        {
            context.Result = new UnauthorizedResult();
            return;
        }

        // Replace this with your actual API key validation logic
        if (!IsValidApiKey(apiKey))
        {
            context.Result = new UnauthorizedResult();
        }
    }

    private bool IsValidApiKey(string apiKey)
    {
        // Implement your API key validation logic here
        // This may involve checking against a database or a list of valid keys
        return apiKey == "your-api-key";
    }
}

You can then use the ApiKey attribute to decorate your API endpoints that require API key authentication. For example:

[ApiController]
[Route("api")]
public class MyApiController : ControllerBase
{
    [HttpGet("secure")]
    [ApiKey] // Apply the ApiKey attribute to secure this endpoint
    public IActionResult SecureEndpoint()
    {
        // Authorized access
        return Ok("Authorized with API key.");
    }
}

In this example, the ApiKeyAttribute checks for the presence of an "Api-Key" header in the incoming request and validates it against a predefined API key (replace with your actual API key validation logic). If the API key is invalid or missing, the attribute returns an "Unauthorized" result.

Please ensure that you replace the placeholder "your-api-key" with the actual API key that you intend to use for your API.

JWT (JSON Web Tokens) Authentication / Bearer Token Authentication (Using OAuth 2.0 or Azure AD)

JWT is a token-based authentication method. Clients include a token in the Authorization header of their requests. The server validates and decodes the token to verify the client's identity. Here's a simplified C# code example:

public async Task<IActionResult> SecureApi()
{
    // Validate and decode JWT token
    var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
    var handler = new JwtSecurityTokenHandler();
    var claims = handler.ReadJwtToken(token).Claims;

    // Check if the token is valid and contains the necessary claims
    if (IsValidToken(claims))
    {
        // Authorized access
        return Ok("Valid JWT token.");
    }
    else
    {
        // Unauthorized access
        return Unauthorized();
    }
}

JWT tokens are versatile and commonly used for authentication and authorization in Azure.

Certificate-Based Authentication

Certificate-based authentication uses X.509 certificates for client verification. Clients provide a client certificate as part of the request, and the server verifies it. Here's a simplified C# code snippet:

public async Task<IActionResult> SecureApi()
{
    // Get the client certificate from the request
    X509Certificate2 clientCert = Request.HttpContext.Connection.ClientCertificate;

    if (IsValidClientCertificate(clientCert))
    {
        // Authorized access
        return Ok("Valid client certificate.");
    }
    else
    {
        // Unauthorized access
        return Unauthorized();
    }
}


Certificate-based authentication provides a strong level of security and is often used for device authentication.

 Securely Connecting to Azure Services with Managed Service Identity (MSI) in C#






Comments

Popular posts from this blog

How to Make a Custom URL Shortener Using C# and .Net Core 3.1

C# and .Net Core 3.1:  Make a Custom URL Shortener Since a Random URL needs to be random and the intent is to generate short URLs that do not span more than 7 - 15 characters, the real thing is to make these short URLs random in real life too and not just a string that is used in the URLs Here is a simple clean approach to develop custom solutions Prerequisite:  Following are used in the demo.  VS CODE/VISUAL STUDIO 2019 or any Create one .Net Core Console Applications Install-Package Microsoft.AspNetCore -Version 2.2.0 Add a class file named ShortLink.cs and put this code: here we are creating two extension methods. public   static   class   ShortLink {      public   static   string   GetUrlChunk ( this   long   key ) =>            WebEncoders . Base64UrlEncode ( BitConverter . GetBytes ( key ));      public   static   long   GetK...

Azure key vault with .net framework 4.8

Azure Key Vault  With .Net Framework 4.8 I was asked to migrate asp.net MVC 5 web application to Azure and I were looking for the key vault integrations and access all the secrete out from there. Azure Key Vault Config Builder Configuration builders for ASP.NET  are new in .NET Framework >=4.7.1 and .NET Core >=2.0 and allow for pulling settings from one or many sources. Config builders support a number of different sources like user secrets, environment variables and Azure Key Vault and also you can create your own config builder, to pull in configuration from your own configuration management system. Here I am going to demo Key Vault integrations with Asp.net MVC(download .net framework 4.8). You will find that it's magical, without code, changes how your app can read secretes from the key vault. Just you have to do the few configurations in your web config file. Prerequisite: Following resource are required to run/complete this demo · ...

AWS FREE ASP.NET CORE (.NET 6.0) HOSTING WITH FREE SSL

  FREE ASP.NET CORE (.NET 6.0) Hosting on AWS (Amazon Web Services) Today I was able to host my asp.net 6.0  + ANGULAR 14 application  on AWS Free  Initial Setup of your AWS Account and your Computer Get ready with your asp.net core 3.1 /.net 6 application Install  "AWS toolkit for visual studio 2022" as  visual studio extensions :  it will be required to deploy smoothly from Visual Studio 2022 itself, your life will be easy. Let's finish the AWS account setup  Get signed up with: its free but it will be required a valid credit card or debit card, they will charge nothing for the free services for 1 year * https://portal.aws.amazon.com/billing/signup#/start/email AWS console  for services and offering http://console.aws.amazon.com/ Create a user in AWS Console:  IAM With the help of AWS Identity and Access Management (IAM), you can control who or what has access to the services and resources offered by AWS, centrally manage fine-grained...