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

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...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...