Adding ASP.NET Identity to an existing project with already managed users table

Viewed 29

I have an existing web api project with a users table. In general User is involved in some key business queries in the system (as other tables keep its 'UserId' foreign key). These days I'm interested in adding Asp.net (core) identity. Basically I've already performed the required steps adding a separate Identity table, managing an additional db context (implementing IdentityDbContext), and also added a JWT token service. It looks that everything works fine. However I am now wondering how should I "link" between the authenticated user (which has logged in through the Identity module) and the user which is found on the other original "business related db". What I was thinking of is that upon login, having the userId retrieved from the original Users table, based on the email which is used as the username and is found on both the original Users table and the new Identity table, and than have it kept as a Claim on the authenticated user. This way, each time the user is calling the API (for an Authorize marked action on the API relevant controller), assuming is authenticated I will have the relevant userId on hand and be able to address and query what ever is needed from the existing business table.

I guess this can work, however I'm not sure regarding this approach and I was wondering if there are any other options?

Regarding the option I've mentioned above, the main drawback I see is that upon the creation of a new user, this should be performed against 2 different tables, on 2 different DBs. In this case, in order to keep this in one unit of work, is it possible to create transaction scope consists of 2 different db contexts?

1 Answers

You're on the right track.

I faced similar problem

Imagine two different microservices.

  • Identity-Microservice(Stores identity information (Username, Password Etc...))

  • Employees-Microservice (Stores employee information (Name, Surname Etc...))

So how to establish a relationship between these two services?

Use queues(RabbitMq, Kafka etc...)

  • An event is created after User Registration(UserCreatedEvent {Id, Name etc..})

  • The workers microservice listens for this activity and records it in the corresponding table

This is the final state

Identity Id = 1, UserName = ExampleUserName, Email = Example@Email Etc...

Employee Id = 1, Name = ExampleName, Surname = ExampleSurname Etc...

Now both services are associated with each other.

Example

If i want to get the information of an employee who is logged in now.

var currentEmployeeId = User.Identity.GetById()

var employee = _db.Employee.GetById(currentEmployeeId)

Related