【问题标题】:Access secured Webapi from another webapi/services with Azure AD使用 Azure AD 从另一个 Web api/服务访问安全 Web Api
【发布时间】:2022-02-18 11:59:51
【问题描述】:

我的 WebAPI 使用 Azure AD 保护

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
...
"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "58ca819e-0e9b-4c72-9ae9-",
    "TenantId": "3a0cf09b-2952-4673-9ace-"
  },
...
[Authorize]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
...

如何在后台从另一个 WebAPI 验证和访问这个 WebAPI?

【问题讨论】:

    标签: asp.net-web-api azure-active-directory


    【解决方案1】:

    我们需要在受保护的 WebApi 中设置应用程序角色:

    为后台 WebAPI 创建新的应用程序注册。

    • 为受保护的 WebAPI 添加权限。在我的 API\Application 权限中,勾选角色管理员。最后授予默认目录。
    • 创建客户端密码。

    这是用于测试的 LINQpad 脚本:

    async Task Main()
    {
        var tennant= "3a0cf09b-";
        // background WebAPI
        var clientId="be7e77ba-";
        var clientSecret = "u9h7Q~izIQZkfJbiCwgxy";
        // secured WebApi
        var apiScope = "api://58ca819e-/.default";
        
        var token = await $"https://login.microsoftonline.com/{tennant}/oauth2/v2.0/token"
            .PostUrlEncodedAsync(new {
                client_id=clientId,
                scope= apiScope,
                client_secret=clientSecret,
                grant_type="client_credentials"
            }).ReceiveJson<MyClass>();
            
        token.Dump();
    
        var data = await "https://localhost:5001/WeatherForecast"
            .WithOAuthBearerToken(token.access_token)
            .GetStringAsync();      
        data.Dump();
    }
    
    class MyClass
    {
        public string access_token{get;set;}
    };
    

    【讨论】:

      猜你喜欢
      • 2019-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多