Search code examples
restmicroservicesazure-service-fabric

How does one pass user context between an API and a microservice?


I am trying to setup audit logging and we were wanting the log event to happen as close to the action as possible, while also knowing which user performed the action. This means we need to pipe in the user info. What are best practices for this?


Solution

  • I'm going to assume you are developing a public internet facing application where your Micro Services are built using ASP.Net Core, and based on that I would suggest the following:

    When setting up SF, have it create two scale sets, one for your public facing micro services ("API Facade" and GUI) and one for your internal Micro services. It's always best to seperate "internet facing code" from "internal code".

    Have Identity Server issue a access token, containing the customer information, for your public "Facade API", and use it when calling your API.

    Your API facade service will act as a proxy for all your internal micro services and offload SSL/Authentication so you don't have to deal with this internaly. This is also where I would recommend that you do the actual audit logging. In your Facade API, create a correlation ID and add it as a header to any calls being made to a internal service. Add the correlation id to any logging being made. This will allow you to follow a API call all the way through your system and together with your audit log, you can see exacly what a user has been doing.

    For auditing, I can recomend Audit.Net. With this you can add a attribute to your controller like this:

    namespace MyWebApi.MyService.Controllers
    {
      [Route("api/[controller]")]
      [AuditApi(EventTypeName = "{controller}/{action} ({verb})")]
      public class MyController : Controller
      {
      }
    }
    

    and it will automaticly handle the audit for your. You can configure it to log blob storgate, file or whatever.

    (I am in no way associated with Audit.Net, I just like it.)