简体   繁体   中英

Add custom roles for blazor Server side with AzureAd

I have a middleware that adds a custom roles to the user after login by using AzureAd , it works fine but I have a problem that after for example I logged in and someone also logged in after me, this user still has the same roles that I added for me, I didn't understand why blazor saving this roles for different user even after signing out and how can that happen and how can I do it in the right way
This is the middleware

public class RoleHandler
{
    private readonly RequestDelegate _next;
    private List<string> Roles { get; set; }

    public RoleHandler(RequestDelegate Next)
    {
        _next = Next;
    }

    public async Task InvokeAsync(HttpContext context, IGenericHttpClient<Role> httpClient)
    {
        if (Roles == null || Roles.Count == 0)
        {
            Roles = await GetRole(context, httpClient);
        }
        else
        {
            foreach (var role in Roles)
            {
                //Add roles to this user, in this case user can be admin or developer ...
                context.User.Identities.FirstOrDefault().AddClaim(new Claim(ClaimTypes.Role, role));
            }
        }
        await _next(context);
    }

    public async Task<List<string>> GetRole(HttpContext context, IGenericHttpClient<Role> httpClient)
    {
        List<string> rolesList = new();
        //Get role from api like [guid, admin]
        var appUserRoles = await httpClient.GetJsonAsync("/api/roles/search?id=XXX");
        //Get role from user as guid
        var RolesString = context.User.Claims
                .Select(c => c.Value).ToList();

        foreach (var appRole in appUserRoles)
        {
            foreach (var role in RolesString)
            {
                if (appRole.RoleString == role)
                {
                    rolesList.Add(appRole.Name);
                }
            }
        }
        return rolesList;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM