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

如何在Azure应用注册中配置Web Core API的OAuth2.0密钥认证

Azure App Registration 配置OAuth2.0客户端密钥保护Web Core API流程

一、注册多租户API应用

  • 登录Azure门户,搜索进入App Registrations,点击New registration
  • 填写注册信息:
    • 名称:自定义API标识名称(如Your-Business-WebAPI)
    • 支持的账户类型:选择Accounts in any organizational directory (Any Azure AD directory - Multitenant)(适配多家企业接入需求)
    • 重定向URI:留空(Web API无需此配置),点击Register完成注册

二、配置API的访问范围

  • 进入已注册应用的Expose an API页面
  • 确认顶部的应用ID URI(默认格式为api://{client-id},可自定义为更易识别的名称,如api://your-business-api),点击Save
  • 点击Add a scope,填写范围配置:
    • 范围名称:如api.access
    • 谁能同意?选择Admins only(企业级API限制管理员授权,避免普通用户随意访问)
    • 管理员同意显示名称/描述:自定义说明(如Access the business web API)
    • 状态设为Enabled,点击Add scope完成配置

三、生成客户端密钥(Client Secret)

  • 切换到Certificates & secrets页面,选择Client secrets标签
  • 点击New client secret:
    • 描述:自定义密钥用途(如API Client Credential)
    • 过期时间:根据安全策略选择(如6个月、12个月或自定义期限)
    • 点击Add后,立即复制生成的密钥值(离开页面后无法再次查看,务必妥善保存)

四、配置Web Core API的验证逻辑

  1. 安装NuGet依赖:Microsoft.AspNetCore.Authentication.JwtBearer
  2. 修改项目的Program.cs(或Startup.cs),添加Azure AD验证配置:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://login.microsoftonline.com/common"; // 多租户场景固定值
        options.Audience = "api://your-business-api"; // 替换为你设置的应用ID URI
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true
        };
    });

builder.Services.AddAuthorization();

// 注册中间件(注意顺序:先认证再授权)
app.UseAuthentication();
app.UseAuthorization();
  1. 在需要保护的控制器或Action上添加[Authorize]属性

五、客户端调用测试

客户端通过客户端凭证流获取AccessToken后调用API:

  • 请求地址:https://login.microsoftonline.com/common/oauth2/v2.0/token
  • 请求方式:POST
  • 表单参数:
    • grant_type: client_credentials
    • client_id: 你的应用注册客户端ID
    • client_secret: 你生成的客户端密钥
    • scope: api://your-business-api/.default(多租户场景需添加.default后缀)
  • 获取AccessToken后,在API请求的Header中携带:Authorization: Bearer {access-token}即可访问受保护接口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:13:25