Search user in local db and add claim to user identity

Viewed 91

I have an internally used Blazor webpage and want to use my Azure AD to authenticate against. After the user is logged in I want to search their name/ID/Something from AzureID in my onsite database and add their employee number so I can use it in the whole program.

Is this the best way?

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(
                    options =>
                    {
                        Configuration.Bind("AzureAd", options);
                        options.Events = new OpenIdConnectEvents();                   
                        options.Events.OnTokenValidated = OnTokenValidatedFunc;
                    }, options => { Configuration.Bind("AzureAd", options); })
                .EnableTokenAcquisitionToCallDownstreamApi(options => Configuration.Bind("AzureAd", options), initialScopes)
                .AddMicrosoftGraph(Configuration.GetSection("GraphAPI"))
                .AddInMemoryTokenCaches();

Which will use the event to search for my EmployeeID

var oid = context.SecurityToken.Payload.FirstOrDefault(z => z.Key == "oid");
// Get the user his ID from the database
var employee = EmployeeLogic.GetEmployee()
                .FirstOrDefault(x => x.AzureObjectId == oid.Value.ToString());

context.Principal?.Identities.FirstOrDefault()?
  .AddClaim(new Claim("EmployeeID", employeeId.ToString(CultureInfo.InvariantCulture)));           

or is there a better way to add something which I can use as Identifier to my local Database.

thanks in advance Maurice

0 Answers
Related