0

I have an asp.net mvc app, and am utilizing the code from the following sample: https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi

After the user is logged in, I would like to add a system admin role claim to the principal claims, and the best place I can figure is in the Startup.Auth.cs :

    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
            {
                try
                {
                    var userEmail = notification.AuthenticationTicket.Identity.
                         Claims.SingleOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
                    if (userEmail != null)
                    {
                        using (var ctx = new DbContext())
                        {
                            var currentUser = ctx.Users.SingleOrDefault(u => u.Email == userEmail);
                            if (currentUser != null && currentUser.IsAdmin)
                            {
                                notification.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Role, Common.Configuration.RoleAdministratorName));
                            }
                        }
                    }

This seems to work, but somehow doesn't feel right to instantiate a new db context just for this in startup.auth. Is this normal practice to do it here?

Riz
  • 6,486
  • 19
  • 66
  • 106
  • Why not get this claim issued into the token via AAD B2C? What logic determines whether the user should be an Admin role? – Jas Suri - MSFT Feb 24 '21 at 21:20
  • it checks in our database whether the user is Admin. The reason why I want the claim in the Identity is so that asp.net Authorize[Role = "Admin"] doesn't break in places. – Riz Feb 24 '21 at 22:29
  • Thanks @Riz and please see the this document when you are using Authorize attribute. https://stackoverflow.com/questions/40302231/authorize-by-group-in-azure-active-directory-b2c Hope this will help for normal practices. – Jit_MSFT Feb 26 '21 at 12:31
  • You could call a REST API during the custom policy to fetch the data and issue it into the token. Then it would be in the principal object. https://learn.microsoft.com/en-us/azure/active-directory-b2c/custom-policy-rest-api-claims-exchange – Jas Suri - MSFT Feb 26 '21 at 22:18

0 Answers0