你了解客户端凭证流,那么你应该知道这种流不需要用户登录生成访问令牌,而只需要一个带有客户端的天蓝色广告应用程序秘密。此 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 role和jwt 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();
}
-
在您的租户和 expose an api 和 a role 中创建一个 azure 广告应用程序。
-
您可以创建另一个 azure ad 应用程序,添加客户端密码并在 API permissions 刀片中添加之前创建的应用程序权限。
-
向那些外部应用程序提供应用程序ID和客户端密码,并让他们使用这些来生成访问令牌,然后他们可以使用访问令牌来调用您的api。
-
如果角色正确,请修改您的 api 以授权令牌。