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

Azure AD SSO + .NET 7 API配置咨询:管理员与角色权限管理

解决方案:.NET7 API 结合 Azure AD SSO 与 AspNetCore.Identity 实现认证授权

一、Azure门户配置步骤

1. 注册API应用程序

  • 登录Azure门户,进入Azure Active Directory → 应用注册 → 新注册
  • 填写应用名称(如MyDotNetAPI),选择账户类型(建议选「仅限此组织目录中的账户」),重定向URI留空(API无需前端跳转),点击注册
  • 注册完成后,记录应用程序(客户端)ID和目录(租户)ID,后续配置会用到

2. 配置API权限

  • 在应用注册页面进入API权限 → 添加权限 → 我的API,选择刚注册的API应用
  • 添加user.read等必要委派权限,点击授予管理员同意确保权限生效

3. 创建默认管理员用户与角色

  • 进入Azure AD的用户 → 新建用户,填写用户名、密码完成创建
  • 回到应用注册的应用角色 → 创建应用角色,添加Admin角色(显示名称「管理员」,值Admin,描述「系统管理员」)
  • 进入企业应用程序,找到刚注册的API应用,进入用户和组 → 添加用户/组,将新建用户添加并分配Admin角色

二、.NET7 API 项目配置

1. 安装必要NuGet包

在项目中执行以下命令安装依赖:

Install-Package Microsoft.Identity.Web
Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer # 若用其他数据库替换为对应提供者

2. 配置appsettings.json

添加Azure AD和数据库连接字符串:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com/",
  "Domain": "你的租户域名",
  "TenantId": "你的租户ID",
  "ClientId": "你的API应用客户端ID"
},
"ConnectionStrings": {
  "DefaultConnection": "Server=.;Database=MyApiAuthDb;Trusted_Connection=True;TrustServerCertificate=True;"
}

3. 配置Program.cs

(1)添加认证与Identity服务

var builder = WebApplication.CreateBuilder(args);

// 配置Azure AD认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

// 配置Identity数据库上下文
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 注册Identity服务
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

// 定义管理员专属授权策略
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});

builder.Services.AddControllers();

(2)创建ApplicationDbContext

新建ApplicationDbContext.cs文件:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : IdentityDbContext<IdentityUser, IdentityRole, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

(3)初始化数据库与角色数据

在Program.cs中添加种子数据初始化逻辑:

var app = builder.Build();

// 初始化数据库与角色
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
    var userManager = services.GetRequiredService<UserManager<IdentityUser>>();

    // 创建Admin角色(不存在则创建)
    if (!await roleManager.RoleExistsAsync("Admin"))
    {
        await roleManager.CreateAsync(new IdentityRole("Admin"));
    }

    // 同步Azure AD管理员到Identity数据库
    var azureAdminObjectId = "Azure AD管理员用户的ObjectId"; // 从Azure门户用户详情获取
    var identityUser = await userManager.FindByIdAsync(azureAdminObjectId);
    if (identityUser == null)
    {
        identityUser = new IdentityUser { Id = azureAdminObjectId, UserName = "admin@yourdomain.com" };
        await userManager.CreateAsync(identityUser);
    }
    // 为用户分配Admin角色
    if (!await userManager.IsInRoleAsync(identityUser, "Admin"))
    {
        await userManager.AddToRoleAsync(identityUser, "Admin");
    }
}

// 中间件配置
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

三、权限与角色管理实现

1. 管理员专属接口示例

创建AdminController.cs,仅允许Admin角色访问:

[ApiController]
[Route("api/[controller]")]
[Authorize(Policy = "AdminOnly")]
public class AdminController : ControllerBase
{
    private readonly UserManager<IdentityUser> _userManager;
    private readonly RoleManager<IdentityRole> _roleManager;

    public AdminController(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
    {
        _userManager = userManager;
        _roleManager = roleManager;
    }

    // 创建新用户
    [HttpPost("create-user")]
    public async Task<IActionResult> CreateUser([FromBody] UserCreateModel model)
    {
        var user = new IdentityUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);
        return result.Succeeded ? Ok("用户创建成功") : BadRequest(result.Errors);
    }

    // 分配角色
    [HttpPost("assign-role")]
    public async Task<IActionResult> AssignRole([FromBody] RoleAssignModel model)
    {
        var user = await _userManager.FindByEmailAsync(model.UserEmail);
        if (user == null) return NotFound("用户不存在");
        var result = await _userManager.AddToRoleAsync(user, model.RoleName);
        return result.Succeeded ? Ok("角色分配成功") : BadRequest(result.Errors);
    }
}

// 辅助模型
public class UserCreateModel
{
    public string Email { get; set; }
    public string Password { get; set; }
}

public class RoleAssignModel
{
    public string UserEmail { get; set; }
    public string RoleName { get; set; }
}

2. Azure AD角色与Identity角色映射

在Program.cs的Azure AD认证配置中,添加角色声明映射:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(options =>
    {
        builder.Configuration.Bind("AzureAd", options);
        options.TokenValidationParameters.RoleClaimType = "roles";
    }, options => { builder.Configuration.Bind("AzureAd", options); });

四、测试认证流程

  1. 获取Azure AD访问令牌:用Postman选择OAuth 2.0授权类型(Authorization Code),填写客户端ID、租户ID、回调URL,权限选api://{你的API客户端ID}/access_as_user,获取令牌
  2. 调用API接口:在请求头添加Authorization: Bearer {你的令牌},调用Admin接口,验证仅管理员用户可访问
  3. 测试用户创建、角色分配功能,检查数据库中AspNetUsers和AspNetUserRoles表的记录是否正确

内容的提问来源于stack exchange,提问作者lolo xoxo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 02:16:07