Skip to content

Instantly share code, notes, and snippets.

@nerdcules
Last active March 16, 2024 21:14
Show Gist options
  • Save nerdcules/97089f72abafe51be1f2e150157746cc to your computer and use it in GitHub Desktop.
Save nerdcules/97089f72abafe51be1f2e150157746cc to your computer and use it in GitHub Desktop.
Securing API
ruM8Q~3ughxh4t7d3pnsvQ2RSAosTLv9LIKFbbiy
secret id:
e54ced5c-ce23-4572-b191-a96b6140d6a8
https://login.microsoftonline.com/1cabd5e8-e68a-4ad8-9a69-7f5f24e92af2/oauth2/v2.0/token

Altering your .NET WebAPI to integrate Azure AD authentication and enriching user claims based on details from an internal API (EIP) involves several detailed steps. Below is a more extensive guide on how to achieve this:

1. Register Your WebAPI in Azure AD

First, ensure your WebAPI is registered in Azure AD:

  1. Sign in to the Azure portal.
  2. Go to Azure Active Directory > App registrations > New registration.
  3. Enter a Name for your API and specify the supported account types.
  4. Leave Redirect URI blank as it's not needed for a WebAPI.
  5. Click Register. Note the Application (client) ID and Directory (tenant) ID.

2. Configure Authentication in Your WebAPI

Use the Microsoft.Identity.Web library to simplify integrating Azure AD authentication:

  1. Install Microsoft.Identity.Web: In your WebAPI project, add the Microsoft.Identity.Web NuGet package.

    dotnet add package Microsoft.Identity.Web
  2. Configure Services: In your Startup.cs or Program.cs, configure the authentication services.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));
    
        services.AddControllers();
        // Add other services as needed
    }
  3. Add Azure AD Configuration: In your appsettings.json, add your Azure AD configuration:

    "AzureAd": {
        "Instance": "https://login.microsoftonline.com/",
        "TenantId": "<Your-Tenant-ID>",
        "ClientId": "<Your-WebAPI-Application-ID>",
        "Audience": "<Your-WebAPI-Application-ID>"
    }
  4. Use Authentication Middleware: Ensure the authentication middleware is used in your application pipeline.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Other configurations...
    
        app.UseAuthentication();
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

3. Secure API Endpoints

Use [Authorize] attributes on your controllers or actions to secure your endpoints:

[Authorize]
[ApiController]
[Route("[controller]")]
public class MySecureController : ControllerBase
{
    // Your actions
}

4. Call the Internal API (EIP) for Additional User Details

When you need to fetch user details from the EIP, ensure this call is secure and authenticated. How you do this depends on the EIP's security requirements (e.g., API keys, client certificates).

public async Task<UserDetails> GetUserDetailsFromEIP(string userId)
{
    // Code to call EIP and fetch user details
}

5. Enrich Claims After Authentication

You might need a custom claims transformation service to add additional claims to the user identity based on the details fetched from EIP:

  1. Implement Claims Transformation:

    public class CustomClaimsTransformation : IClaimsTransformation
    {
        public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var identity = principal.Identity as ClaimsIdentity;
    
            // Call your EIP to get additional user details
            // UserDetails userDetails = await GetUserDetailsFromEIP(userId);
    
            // Add a custom claim
            // identity.AddClaim(new Claim("custom-claim", userDetails.SomeValue));
    
            return Task.FromResult(principal);
        }
    }
  2. Register Your Claims Transformation in Startup.cs or Program.cs:

    services.AddTransient<IClaimsTransformation, CustomClaimsTransformation>();

6. Apply Authorization Based on Claims

You can now authorize access to your API endpoints based on the enriched claims:

[Authorize(Policy = "CustomPolicyBasedOnClaims")]
public class SecureController : ControllerBase
{
    // Your secure actions
}

And define the policy in Startup.cs or Program.cs:

services.AddAuthorization(options =>
{
    options.AddPolicy("CustomPolicyBasedOnClaims", policy =>
        policy.RequireClaim("custom-claim", "expected-value"));
});

Final Steps and Testing

  • Test your API using tools like Postman or a front-end application to ensure that authentication and authorization work as expected.
  • Ensure to handle error cases gracefully, such as when the EIP is not available or returns unexpected data.
  • Use logging to help debug any issues related to authentication or claims transformation.

By following these steps, you'll integrate Azure AD authentication into your WebAPI, secure your endpoints, and enrich user claims for fine-grained authorization.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment