我正在尝试用 C# 编写 ASP.NET Core 6 MVC 控制器方法,该方法将根据分配给用户的 Azure AD 组将 Azure AD 身份验证用户重定向到子域。
任何专家都可以建议我如何实现这一目标吗?
首先需要获取Azure组ID,因为token不支持发送组名,所以必须使用id来区分。
在应用程序注册中创建客户端后,进入客户端“Token配置”将群组信息添加到声明中
然后您可以使用“Microsoft 身份平台”身份验证类型创建 MVC 模板项目进行测试。
在appsettings中填写客户端信息。
创建一个
CustomMiddleware.cs
(将usergroups.Contains("group id")
修改为你的groupid,并修改重定向domian)
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
var usergroups = new List<string>();
var claims = httpContext.User.Claims;
foreach (var c in claims)
{
if (c.Type == "groups")
{
usergroups.Add(c.Value);
}
}
if (usergroups.Contains("{group id}"))
{
httpContext.Response.Redirect("https://www.google.com"); //change to the corresponding subdomain.
}
await _next(httpContext);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class CustomMiddlewareExtensions
{
public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomMiddleware>();
}
}
将中间件添加到program.cs
...
app.UseCustomMiddleware();
app.Run();
然后,如果登录用户具有 {gourp id} 声明,则该用户将被重定向。