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_APIto access controller methods that require the Admin role.User_Neighbor_APIto 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.JwtBearerNow, 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
Adminrole access. - One for
Userrole 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):
- Generate a JWT token for
Adimin_Neighbor_APIwith theAdminrole. - Send a GET request to the
AdminController:
curl -H "Authorization: Bearer <adminToken>" https://your-api.com/api/admin/get-admin-dataIf the token is valid and contains the
Admin role, the API will return:{
"message": "This is Admin data."
}
For User_Neighbor_API (User):
- Generate a JWT token for
User_Neighbor_APIwith theUserrole. - Send a GET request to the
UserController:
curl -H "Authorization: Bearer <userToken>" https://your-api.com/api/user/get-user-dataIf 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-dataIt 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
Post a Comment