Role Based Authentication and authorization in .NET 8 WEB API
Table of Contents
Introduction
This tutorial will guide you through implementing Role-Based Authentication and Authorization in a .NET 8 Web API. Role-based access control is essential for managing user permissions efficiently, ensuring that users can only access resources appropriate to their roles. By the end of this guide, you'll have a foundational understanding of how to set up and use role-based authentication in your applications.
Step 1: Set Up Your .NET 8 Web API Project
-
Create a new Web API project:
- Open your terminal or command prompt.
- Run the following command to create a new project:
dotnet new webapi -n RoleBasedAuthDemo
- Navigate into the project directory:
cd RoleBasedAuthDemo
-
Install necessary packages:
- Add the required NuGet packages for authentication:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer dotnet add package Microsoft.IdentityModel.Tokens
- Add the required NuGet packages for authentication:
Step 2: Configure Authentication in Startup
-
Open the
Program.cs
file and set up JWT authentication:- Add the following using directives at the top:
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text;
- Add the following using directives at the top:
-
Configure services:
- In the
builder.Services
section, add the authentication services: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 = "YourIssuer", ValidAudience = "YourAudience", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("YourSecretKey")) }; });
- In the
Step 3: Define User Roles
-
Create a user roles enum:
- In a new file, define user roles:
public enum UserRole { Admin, User }
- In a new file, define user roles:
-
Create a model for user:
- Define a User model that includes roles:
public class User { public string Username { get; set; } public UserRole Role { get; set; } }
- Define a User model that includes roles:
Step 4: Implement Role-Based Authorization
- Create a controller:
- In the
Controllers
directory, create aUsersController.cs
file:[ApiController] [Route("[controller]")] public class UsersController : ControllerBase { [Authorize(Roles = "Admin")] [HttpGet("admin")] public IActionResult GetAdminData() { return Ok("This is admin data"); } [Authorize(Roles = "User")] [HttpGet("user")] public IActionResult GetUserData() { return Ok("This is user data"); } }
- In the
Step 5: Testing Role-Based Access
-
Run your application:
- Start your application using:
dotnet run
- Start your application using:
-
Test endpoints using Postman or a similar tool:
- Attempt to access the
/users/admin
endpoint with an admin token and the/users/user
endpoint with a user token to verify the role-based restrictions.
- Attempt to access the
Conclusion
In this tutorial, you learned how to set up role-based authentication and authorization in a .NET 8 Web API. You created a project, configured JWT authentication, defined user roles, and implemented role-based access control in your API. For next steps, consider exploring how to manage user roles dynamically or integrate a database for user management.