Skip to main content

Role-Based Access : Provide access to third-party APIs from Own API Controllers in .NET Core

 

In this blog, we will walk through how to set up role-based access for two third-party applications (Adimin_Neighbor_API and User_Neighbor_API) to your .NET Core application, MYOWN_API. The goal is to allow:

  • Adimin_Neighbor_API to access controller methods that require the Admin role.
  • User_Neighbor_API to access methods that require the User role.

We'll use JWT Authentication with role-based authorization to implement this.

Prerequisites

  • .NET Core 6 or later installed.
  • Basic understanding of ASP.NET Core MVC and JWT.

Step 1: Set Up JWT Authentication

To enable JWT-based authentication, we need to install the Microsoft.AspNetCore.Authentication.JwtBearer NuGet package:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Now, configure JWT authentication in Program.cs:
var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllers();
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = "MYOWN_API",  // Change to your actual issuer
        ValidAudience = "MYOWN_API_Audience", // Change to your actual audience
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Your-Secret-Key-Here"))
    };
});

// Configure Role-based authorization
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminPolicy", policy =>
        policy.RequireRole("Admin"));

    options.AddPolicy("UserPolicy", policy =>
        policy.RequireRole("User"));
});

var app = builder.Build();

// Enable Authentication and Authorization middleware
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

Step 2: Define Controller Access Based on Roles

Now that authentication and authorization are set up, we need to secure our controllers. We'll configure two controllers:

  • One for Admin role access.
  • One for User role access.

AdminController for Adimin_Neighbor_API (Admin Access):

[Authorize(Policy = "AdminPolicy")]
[ApiController]
[Route("api/[controller]")]
public class AdminController : ControllerBase
{
    [HttpGet("get-admin-data")]
    public IActionResult GetAdminData()
    {
        // Logic for fetching admin-specific data
        return Ok(new { message = "This is Admin data." });
    }
}

Step 3: Generating JWT Tokens with Roles

You'll need to generate JWT tokens for Adimin_Neighbor_API and User_Neighbor_API with appropriate roles. Here's an example of how to generate JWT tokens in MYOWN_API:

public class AuthService
{
    public string GenerateToken(string username, string role)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Your-Secret-Key-Here"));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.Role, role)
        };

        var token = new JwtSecurityToken(
            issuer: "MYOWN_API",
            audience: "MYOWN_API_Audience",
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: credentials);

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}
To generate tokens for the Admin and User roles:
var authService = new AuthService();

// Generate token for Adimin_Neighbor_API (Admin)
string adminToken = authService.GenerateToken("AdminUser", "Admin");

// Generate token for User_Neighbor_API (User)
string userToken = authService.GenerateToken("NormalUser", "User");

The third-party APIs (Adimin_Neighbor_API and User_Neighbor_API) will use these tokens to access your protected controllers.

Step 4: Testing the Role-Based Authorization

Now that you've implemented role-based authorization, let’s test it. Here's a sample request flow:

For Adimin_Neighbor_API (Admin):

  1. Generate a JWT token for Adimin_Neighbor_API with the Admin role.
  2. Send a GET request to the AdminController:
curl -H "Authorization: Bearer <adminToken>" https://your-api.com/api/admin/get-admin-data
If the token is valid and contains the Admin role, the API will return:
{
    "message": "This is Admin data."
}

For User_Neighbor_API (User):

  1. Generate a JWT token for User_Neighbor_API with the User role.
  2. Send a GET request to the UserController:
curl -H "Authorization: Bearer <userToken>" https://your-api.com/api/user/get-user-data
If the token is valid and contains the User role, the API will return:
{
    "message": "This is User data."
}

Step 5: Handling Unauthorized Access

If a third-party API tries to access a controller or action it is not authorized for, the API will return a 403 Forbidden response.

For example, if User_Neighbor_API tries to access the AdminController:

curl -H "Authorization: Bearer <userToken>" https://your-api.com/api/admin/get-admin-data
It will return a 403 Forbidden response since User_Neighbor_API does not have the Admin role.

Conclusion

By implementing JWT Authentication with role-based authorization, you can ensure that third-party APIs like Adimin_Neighbor_API and User_Neighbor_API only have access to the parts of your MYOWN_API application that they are authorized for. This not only secures your application but also ensures that sensitive data is only accessible by the appropriate parties.

Key Takeaways:

  • Use JWT tokens for authentication and include role claims to define access.
  • Implement policies based on roles to secure your controllers.
  • Test your API to ensure the roles are properly enforced.

This method provides flexibility and security, ensuring that only authorized third-party applications can access specific functionality based on the roles you assign.

Comments

Popular posts from this blog

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...