Posts

Showing posts from 2024

Registering Multiple Implementation With Same Interface

Image
We have an interface with name  IVehicle public interface IVehicle { string Type { get ; set ; } } We have 3 Implementations of this interface  Car , Van  and  Truck . public class Car : IVehicle { public string Type { get ; set ; } = "Car" ; } public class Truck : IVehicle { public string Type { get ; set ; } = "Truck" ; } public class Van : IVehicle { public string Type { get ; set ; } = "Van" ; } We have a  CarController , where we want to use the  Car  implementation of  IVehicle . [ Route( "/api/cars" ) ] [ ApiController ] public class CarController : ControllerBase { private IVehicle _vehicle; public CarController ( IVehicle vehicle ) { _vehicle = vehicle; } } It is a usual approach to inject any service. But, in our case  IVehcle  have 3 implementations.However, determining which implementation is in use is not straightforward with our current method. To address this,

Asp.net core JWT authentication and role-based authorization (.NET 8.0)

Image
  Let's take the example of an eCommerce application. It is a single-page application built with a JavaScript framework like Angular, React, Vue, or Svelte. Data is being handled through APIs. On the home page, products are displayed (e.g., the data is being fetched from the GetAllProducts API). Everyone can see these products, but not everyone can add, update, or delete them. Only authorized users can perform these actions. These tasks will be assigned to specific users. For example, the AddProduct , UpdateProduct , and DeleteProduct APIs need some kind of protection. We have several options to protect our API. You can use cookie authentication or token-based authentication. We are not going to cover the benefits or downsides of each authentication method. Instead, we will focus only on token-based authentication. For which we are going to use  JWT   aka  JSON WEB TOKEN . Json Web Token A compact, URL-safe token format that contains a set of claims and is signed using a secret k