Implementing Microservice Architecture In .NET Part 3 , Product Service

Reza Mansouri
5 min readNov 24, 2022

--

Hello everyone :)

Last Articles:

Implementing Microservice Architecture In .NET Part 1 , Project Overview

Implementing Microservice Architecture In .NET Part 2 , Auth Service by JWT Token

at the last article we develop the AuthService to register user and get jwt token for authentication and authorization.

in this section we develop ProductMicroservice that is for get and manage products.

we have three controllers in this microservice

CategoryController : for add and get product category , have two action

  1. Get() returns all category by call GetCategories From CategoryService
  2. Post() add category by call AddNewCatrgory From CategoryService

ProductController : for get products info , have two actions

  1. Get() returns all products by call GetProductList From ProductService
  2. Get(Guid id) returns one product by call GetProduct(id) From ProductService

ProductManagementController : for manage products , add edit and delete products by ProductService

here we must authorize user role in ProductManagementController , the role for manage products is “Admin” Role , so we add the filter

[AutenticationFilter( Roles =”Admin”)]

in ProductManagementController

  public override void OnActionExecuting(ActionExecutingContext context)
{

HttpContextAccessor _httpContextAccessor = new HttpContextAccessor();

var userInfo = TokenManagerService.GetUserInfo(_httpContextAccessor);
if (string.IsNullOrEmpty(userInfo.UserName))
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Result = new JsonResult("Pelase Send Valid Token In Request Header :| "); ;
}
if (!string.IsNullOrEmpty(Roles) && !string.IsNullOrEmpty(userInfo.UserName))
{
var AllUserrole = userInfo.Roles?.Split(",");
if ( !AllUserrole.Contains(Roles))
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Result = new JsonResult("This User Must have Role " + Roles + " :| "); ;
}
}
base.OnActionExecuting(context);
}

in OnActionExecuting we get user info by TokenManagerService.GetUserInfo , if user info data has value, then check the role , if user have the role we will continue our work , else we return Unauthorized ( 403 ) status code .

for check these operations we need to send token in header of our request , for do this in swagger we add a config to can add token in swagger request.

 public class AuthenticationHeadersFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
operation.Parameters.Add(new OpenApiParameter
{
Name = "token",
In = ParameterLocation.Header,
Required = false
});
}
}

and add in Program.cs

builder.Services.AddSwaggerGen(c =>
{
c.OperationFilter<AuthenticationHeadersFilter>();
});

so , we run projects.

if you have problem to run project see How Run Project in first article

first we must get token in AuthMicroservice that is run on https://localhost:7147/swagger/index.html

if we have been register before , do login request and send mobile( username) and password to get token , if not register before first execute register command and then send login command to get token.

after that we have encrypted token like this

i9L+OZDYvCEC3z2yKEgFtP8C60iKUhNZlfqC64ZdBOOeAVgX0+TSjP66w3HKVS8+HEospeVsN6zr+l9tdH4xJXuMzOpjpwmt3XFeacCCb16kcDo5zex8BlVKdrZxOJWhkJwi6VnMCV11DtWj7oxpX4ctw1N3hUa/7b3rB7WtHDITAR2ELpZMXIyTi867oNynf1TxK3GJ0k8qPBe+Fto62dvPNpLDXaQAViGArm8ljBcVkR6ZtwsUCFcL8yd16yL++1K3n72mdiEH1vFuhNuwAKqPNzdiyn6blCSeVhIMT9dR8Z0YRJKDzoRd5Z1YFU9EJ5QkcJGCWVOP4i6uZgNeKTBClFC6ytkNm1MZd9N+ePsyddhtGiP40EFAqW3K99ljyLUjhn4pcjFRQhbfZzAzIHABOlBL0bwBQoMfDiiFG7ztvDwHUir/rHg+ogHs0DD9Bkfj/jGRLdkIHhWHBKhgFeXhX5urx+f8oV41QIhux4r0yMKAik6cqB93UO35/gQMKnJa6J6vp79onvAhVM5N0kfH68DrSq6YvgacHUgrT7xZrqX8gVODux2x+VhomIgpJC/PFe24/nfS58WWyuzUx1aPgN8cBpTNNGfmEkUUOWMEIHOCdbr5pow5dmYJ/+yEOTasR+lZMkyCU1l37cs2OjU41BM+6x+99SjitzjmdfAVwFmF4Ryu0oFbYSE0rTwAHafvmg98n6ae0zE66n5RZOJ+zLlSSIfr4XqHFDjgYlUgdbuJL8AAvoRONEsZ1kxj+67shZGgjwTKfxLs6N+KelT/VLhj4q1e9/rNEmDTSR0yudH7vtfRAFNmk3rjnSvI5L5UYiAJ8yTypUfPkLMtTv+jp5daAXYrDEWgiXbuZCE6rK1sdY+3GHARrvpgWeE928ASleN5miys2S7B/xsUXatIAcriQPHwWMfN53WyuchzlkeeCrJxbdpJPc+gZSOx3aIUvQWmvHXaR59NB0P14DcrqBNWBKsgyLf8xDGRUiCnxW9wBk3aupvHhMsk2wr3W5q2Megll0G+F3x6k5eKLgh12EhjLtZDkyQzXxICOykYiSOXK2H77OyXrHC4daL+BDqxGAZl+b6xovcUMAcMBZw7/hzM1RlUN9HQauzPHgkBd6d1Q5TL6I6vpoLRALZLczfIqJV3UdTY6emA6LmLKVTy6tPjdEMYfgVTQw7ojvFK+hASrZlx8Yr80P0DYzsAXP+/OJKCQAVUubRyn3MFrg==

then we move to ProductService Swagger tab in https://localhost:7061/swagger/index.htm address and call “/api/caregory” post method

before send request , put our token in token textbox in request and fill the data of our category , the name and description

send request and will get 401 status code !

why? Because our user by default have User role and in the action check the user must have Admin role , for resolve this when add Admin role in AuthDb Sql Databse And User table , we update role field to “User,Admin” to set User And Admin role for user and get new token again from login request ( it’s important to get token again because the current token do not have Admin role in the body of jwt token) and set it in token textbox in our request , then send request again.

we get the 200 status code and our category save on ProductDB DataBase , Categories table .

after that, we can add products , call the “​/api​/ProductManagement” Post action for add product and do not forget to put the token on the token text box and set categoryid in request body from our category id from database.

the result is 201 status code mean created and we can see the product in Products table on ProductDB database.

we do this call several time to have more products .

so, we add category and products in database , for manage products we cane use other request , also remember we set

[AutenticationFilter( Roles =”Admin”)]

filter in top of ProductManagementController and must put token have admin role in request , but in get request for products and get request for category , no need to put token , because this actions no need authentication and authorization.

At the end of this article, we have done our ProductMicroservice.

our next job is developing BasketMicroservice which uses ProductMicroservice to get product data and add it to the basket and so on.

Of course, we still have a lot of work to do, but you can see the full source of these articles here.

I hope you like this article :)

--

--