【问题标题】:azure oauth 2.0 how to protect web api from external organization web api?azure oauth 2.0 如何保护 web api 免受外部组织 web api 的影响?
【发布时间】:2022-01-17 14:34:10
【问题描述】:

我是 Azure 的新手,正在尝试使用 oauth 2.0 保护托管在 azure 中的/web api。 这个 web api 将被其他组织控制的其他 web api/deamon 调用。 我知道客户端凭据流,但在这种情况下,外部 api 托管在天蓝色广告之外。我们不知道它的托管位置以及第三个外部 Web api/deamon 是如何托管的?我们应该如何对我们的 web api 进行身份验证/授权,以便任何外部服务都可以使用它?

【问题讨论】:

  • 先生,您对此案还有什么顾虑吗?

标签: azure oauth-2.0 azure-active-directory asp.net-core-webapi msal


【解决方案1】:

你了解客户端凭证流,那么你应该知道这种流不需要用户登录生成访问令牌,而只需要一个带有客户端的天蓝色广告应用程序秘密。此 azure 广告应用程序可以来自您的租户,因此它不需要 web api/deamon which is in control of other organization 拥有应用程序,您可以在租户中创建应用程序,然后将其提供给外部 Web api。您需要确保外部确实是一个守护程序应用程序。

假设需要调用受 azure ad 保护的 api 的外部应用程序是守护程序应用程序,则此处适合客户端凭据流。

外部api生成访问令牌的代码

//you can see it when you add api permission
var scopes = new[] { "api://exposed_apis_app_id/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";
// using Azure.Identity;
var options = new TokenCredentialOptions{AuthorityHost = AzureAuthorityHosts.AzurePublicCloud};
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var tokenRequestContext = new TokenRequestContext(scopes); 
var token = clientSecretCredential.GetTokenAsync(tokenRequestContext).Result.Token;

为你的api添加azure ad认证的代码,你还有一些配置,你可以参考我的this answer,一些相关文档:authorize the token with rolejwt token configuration

    [Authorize]
        public class HelloController : Controller
        {
            public IActionResult Index()
            {
                HttpContext.ValidateAppRole("User.Read");//You set it when adding app role
                Student stu = new Student();
                stu.age = 18;
                return Json(stu) ;
            }
        }

appsettings:
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "ClientId": "2c0xxxxxxx57",
    "Domain": "tenantname.onmicrosoft.com", // for instance contoso.onmicrosoft.com. Not used in the ASP.NET core template
    "TenantId": "common",
    "Audience": "8fxxxx78"
  }

startup.cs, don't forget "app.UseAuthentication();app.UseAuthorization();" in Configure method
public void ConfigureServices(IServiceCollection services)
{
     services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
     services.AddControllersWithViews();
}
  1. 在您的租户和 expose an apia role 中创建一个 azure 广告应用程序。

  2. 您可以创建另一个 azure ad 应用程序,添加客户端密码并在 API permissions 刀片中添加之前创建的应用程序权限。

  1. 向那些外部应用程序提供应用程序ID和客户端密码,并让他们使用这些来生成访问令牌,然后他们可以使用访问令牌来调用您的api。

  2. 如果角色正确,请修改您的 api 以授权令牌。

【讨论】:

    猜你喜欢
    • 2016-09-24
    • 2015-02-07
    • 2022-01-09
    • 2017-02-10
    • 1970-01-01
    • 2012-12-20
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多