[英]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我有一个中间件,可以在登录后使用
AzureAd
向用户添加自定义角色,它工作正常,但我有一个问题,例如在我登录并且有人也在我之后登录后,该用户仍然具有与我相同的角色为我添加,我不明白为什么 blazor 即使在退出后也会为不同的用户保存这个角色,这怎么会发生,我该如何以正确的方式做到这一点
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;
}
}
You should use AddScoped
when you register HttpClient service in Startup.cs
file.在
Startup.cs
文件中注册 HttpClient 服务时应使用AddScoped
。
Related Post:相关帖子:
1. AddTransient, AddScoped and AddSingleton Services Differences 1. AddTransient、AddScoped 和 AddSingleton 服务的区别
2. Cannot Consume Scoped Service From Singleton – A Lesson In ASP.NET Core DI Scopes 2. 无法使用 Singleton 中的作用域服务 – ASP.NET 核心 DI 作用域中的一课
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.