Scenario: I'm building an application with a Blazor server front end with a service layer and EF Core backend. I am using AzureAD w/Accounts for authentication and intercept the authentication stack on the way back up by handling IClaimsTransformation.TransformAsync and adding some custom logic there. I have added audit fields to my entities (CreatedBy, LastModifiedBy) and would like to have those automatically filled in at the EF layer.
Problem: I have tried injecting the AuthenticationStateProvider into my DbContext but when used to retrieve the state, it errors out that the state has to be set first. I can retrieve the auth provider in the blazor "layer" (auth "context" created by App.razor) and of course it's filled in, but there's some magic happening I don't understand, and I'm not sure I can get data from the blazor "context" to the "outside" world of my data layer. As I write this, I realize I need to go back to the MS docs, because the answer is most likely there and I skimmed over it, but if anyone feels like chiming in, please do!
Current Annoying Workaround: Meanwhile, I'm setting the entity audit fields "manually" when creating/updating the entities in the blazor layer.
I am also frustrated that I can't add AuthenticationStateProvider as a tag b/c I'm not contributing to SO enough, but ok, yeah, I get it.
Why would you try and do this in the Infrastructure layer of your application? Its purpose is persisting data to and getting data from data stores. It shouldn't be modifying data.
If you've built a data pipeline for your application, then you should be doing this within the pipeline. If all your data objects that require Audit fields implement say a
IRecordAuditinterface, you can plug a module into the pipeline to detect objects that implement said interface and add the relevant fields. In the pipeline you should be accessing either theAuthenticationStateor your ownUserServicethat gets populated when the user logs in. I'm assuming you can't do CUD operations until you are logged in.I'm talking very high level here because there's no context in your question, and demonstrating how you would implement this is way beyond the scope of a SO answer.
PS - why would you want to add a
AuthenticationStateProvidertag? It sooo specific. Tags are groups that people like me monitor. There are already too many for Blazor.