DEV Community

Cover image for Implementing authorization in a Dotnet API with AuthAction
AuthAction Developer for AuthAction

Posted on

Implementing authorization in a Dotnet API with AuthAction

AuthAction is a powerful authentication and authorization platform that offers a range of features, including support for single-page applications (SPA) and machine-to-machine (M2M) applications. It provides an easy-to-use interface for managing users, roles, and organizations, and supports OAuth2, social logins and passkey authentication. Best of all, AuthAction is scalable, allowing up to 1 Million monthly active users for free. Whether you're developing an app for a startup or a large enterprise, AuthAction provides a flexible and secure solution for your authentication needs.

In this blog, we'll explore how to authorise .Net APIs using AuthAction.

Prerequisites

Before you begin, ensure you have:

  1. .NET 8.0 SDK or later: Download from dotnet.microsoft.com
  2. AuthAction Account: You'll need your AuthAction tenant domain and API identifier

Configuration

1. Install Required Packages

Add the following NuGet packages to your project:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Microsoft.IdentityModel.Protocols.OpenIdConnect
Enter fullscreen mode Exit fullscreen mode

2. Configure AuthAction Settings

Add the following configuration to your appsettings.json:

{
  "Auth": {
    "Authority": "https://your-authaction-tenant-domain/",
    "Audience": "your-authaction-api-identifier"
  }
}
Enter fullscreen mode Exit fullscreen mode

Replace:

  • your-authaction-tenant-domain with your AuthAction tenant domain
  • your-authaction-api-identifier with your API identifier

3. Configure JWT Authentication

In your Program.cs, add the following configuration:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = builder.Configuration["Auth:Authority"];
        options.Audience = builder.Configuration["Auth:Audience"];
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true
        };
    });

builder.Services.AddAuthorization();

// ... other service configurations ...

app.UseAuthentication();
app.UseAuthorization();
Enter fullscreen mode Exit fullscreen mode

Usage

1. Protect Your Endpoints

Add the [Authorize] attribute to your controllers or actions that require authentication:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [Authorize]
    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        // Your protected endpoint logic
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Testing the API

To test your protected endpoints, you'll need to:

  1. Obtain an Access Token

Use the client credentials flow to get a token:

   curl --request POST \
   --url https://your-authaction-tenant-domain/oauth2/m2m/token \
   --header 'content-type: application/json' \
   --data '{
     "client_id": "your-authaction-m2m-app-clientid",
     "client_secret": "your-authaction-m2m-app-client-secret",
     "audience": "your-authaction-api-identifier",
     "grant_type": "client_credentials"
   }'
Enter fullscreen mode Exit fullscreen mode
  1. Call Protected Endpoints

Use the token to access protected endpoints:

   curl --request GET \
   --url http://localhost:5287/protected \
   --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
Enter fullscreen mode Exit fullscreen mode

Security Features

The implementation includes:

  • JWT token validation using AuthAction's JWKS endpoint
  • RS256 algorithm for token signing
  • Automatic token validation and expiration checking
  • Secure configuration management
  • HTTPS support in production

Common Issues

Invalid Token Errors

  • Ensure your token is signed with RS256 algorithm
  • Verify the token contains correct issuer and audience claims
  • Check that Authority and Audience are correctly set in configuration

Public Key Fetching Errors

  • Verify your application can reach AuthAction's JWKS endpoint
  • The JWKS URI should be: https://your-authaction-tenant-domain/.well-known/jwks.json

Unauthorized Access

If requests to protected endpoints fail, check:

  • The JWT token is included in the Authorization header
  • The token is valid and not expired
  • The token's audience matches your API identifier
  • The token's issuer matches your AuthAction domain

Conclusion

Integrating authorization into a .net application using AuthAction is a straightforward process. This example helps streamline the setup, offering developers a robust foundation to build secure applications with minimal effort.

If you run into any issues, double-check your configurations to ensure everything is set up correctly. Happy coding!

Feel free to leave your thoughts and questions in the comments below!

Top comments (1)

Collapse
 
jaythawme profile image
Jaythawme

Very helpful👍, thanks for your sharing!