You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于C# .NET Framework在ASP.NET中通过组ID实现Microsoft Entra ID认证授权

ASP.NET Web Forms 集成 Microsoft Entra ID 组权限控制方案

1. 配置 OWIN 认证中间件

首先安装所需 NuGet 包:Microsoft.Owin.Security.OpenIdConnect、Microsoft.Owin.Security.Cookies、Microsoft.Owin.Host.SystemWeb。

在项目根目录创建 Startup.cs,配置 OpenID Connect 认证流程,确保获取用户组声明:

using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using System.Configuration;
using System.IdentityModel.Tokens;

[assembly: OwinStartup(typeof(YourProject.Startup))]
namespace YourProject
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId = ConfigurationManager.AppSettings["EntraClientId"],
                Authority = $"https://login.microsoftonline.com/{ConfigurationManager.AppSettings["EntraTenantId"]}",
                RedirectUri = ConfigurationManager.AppSettings["EntraRedirectUri"],
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["EntraRedirectUri"],
                ClientSecret = ConfigurationManager.AppSettings["EntraClientSecret"],
                ResponseType = "code id_token",
                Scope = "openid profile email Groups.Read.All",
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    // 将组声明映射为角色(可选,便于后续授权配置)
                    RoleClaimType = "groups"
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = n =>
                    {
                        n.HandleResponse();
                        n.Response.Redirect("/Error.aspx?msg=" + n.Exception.Message);
                        return System.Threading.Tasks.Task.CompletedTask;
                    }
                }
            });
        }
    }
}

在 Web.config 中添加配置项:

<appSettings>
  <add key="EntraClientId" value="你的Client ID"/>
  <add key="EntraTenantId" value="你的租户ID"/>
  <add key="EntraClientSecret" value="你的Client Secret"/>
  <add key="EntraRedirectUri" value="https://你的应用域名/"/>
</appSettings>

2. 获取用户所属组ID

用户认证后,组ID会包含在Claims中(需提前在Entra ID应用的「Token configuration」中添加groups声明,选择返回安全组ID)。可通过以下代码获取:

var userGroupIds = System.Web.HttpContext.Current.User.Claims
    .Where(c => c.Type == "groups" || c.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/groups")
    .Select(c => c.Value)
    .ToList();

3. 实现组权限校验逻辑

方式1:自定义页面基类(适用于Web Forms页面)

创建基类页面,所有需要权限控制的页面继承此类:

public class GroupAuthorizedPage : System.Web.UI.Page
{
    // 子类可重写此属性指定允许的组ID
    protected virtual List<string> AllowedGroupIds => new List<string>();

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        ValidateGroupPermission();
    }

    private void ValidateGroupPermission()
    {
        if (!User.Identity.IsAuthenticated)
        {
            Response.Redirect("/Account/Login.aspx");
            return;
        }

        var userGroups = User.Claims
            .Where(c => c.Type == "groups" || c.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/groups")
            .Select(c => c.Value)
            .ToList();

        if (!AllowedGroupIds.Intersect(userGroups).Any())
        {
            Response.Redirect("/Unauthorized.aspx");
        }
    }
}

示例:管理员页面继承基类并指定允许的组ID:

public partial class Admin_Dashboard : GroupAuthorizedPage
{
    protected override List<string> AllowedGroupIds => new List<string> { "你的管理员组ID" };
}

方式2:Web.config 文件夹级权限控制

如果某个文件夹下的所有页面都需要同一组权限,可在 Web.config 中配置:

<location path="AdminModule">
  <system.web>
    <authorization>
      <deny users="?"/>
      <!-- 直接使用组ID作为角色(需在Startup中配置RoleClaimType为groups) -->
      <allow roles="你的管理员组ID"/>
      <deny users="*"/>
    </authorization>
  </system.web>
</location>

4. 关键注意事项

  • 确保在Entra ID应用中添加Groups.Read.All权限并授予管理员同意。
  • 如果ID Token未返回组声明,需在Entra ID应用的「Token configuration」页面手动添加groups声明,选择「Security groups」并设置返回ID。
  • 敏感操作需在服务器端做权限校验,避免依赖客户端逻辑。

内容的提问来源于stack exchange,提问作者Lokini kunalan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:33:11