我的 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?
我们需要在安全的 WebApi 中设置应用程序角色:
为后台WebAPI创建新的应用程序注册。
这是用于测试的 LINQpad 脚本:
async Task Main()
{
var tenant = "3a0cf09b-";
// background Web API
var clientId = "be7e77ba-";
var clientSecret = "u9h7Q~izIQZkfJbiCwgxy";
// secured Web API
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; }
};