我正在尝试使用azure活动目录来保护我的web api。
我有以下代码来设置web api:
public void BuildConfiguration(IAppBuilder appBuilder)
{
var HttpConfiguration = new System.Web.Http.HttpConfiguration();
HttpConfiguration.Filters.Add(new AuthorizeAttribute());
HttpConfiguration.MapHttpAttributeRoutes();
HttpConfiguration.Routes.MapHttpRoute("DefaultApi",
$"api/{{controller}}/{{action}}/{{id}}", new { id = RouteParameter.Optional });
var authenticationProvider = new OAuthBearerAuthenticationProvider()
{
OnValidateIdentity = AuthenticationOnValidateIdentity
};
var options = new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = "https://xxx.onmicrosoft.com/yyy"
},
Tenant = "xxx.onmicrosoft.com",
Provider = authenticationProvider
};
appBuilder.UseWindowsAzureActiveDirectoryBearerAuthentication(options);
appBuilder.UseCors(CorsOptions.AllowAll);
appBuilder.UseWebApi(HttpConfiguration);
HttpConfiguration.EnsureInitialized();
}
现在,执行验证的代码如下所示:
private async Task AuthenticationOnValidateIdentity(OAuthValidateIdentityContext context)
{
context.Ticket.Identity.AddClaim(new Claim("apikey", xx)); // <- what to put here instead of xx?
}
客户端使用以下代码请求令牌:
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenAsync("https://xx.onmicrosoft.com/yyy", clientId, redirectUri, new PlatformParameters(PromptBehavior.Always), UserIdentifier.AnyUser);
}
catch (AdalException ex)
{
...
}
如何将附加信息(如apikey(字符串))传递给AAD验证器,以便我可以访问“AuthenticationOnValidateIdentity&#39;”中的apikey?
我尝试了extraQueryParameters
参数,例如:
result = await authContext.AcquireTokenAsync("https://xxx.onmicrosoft.com/yyy",
clientId,
redirectUri,
new PlatformParameters(PromptBehavior.Always),
UserIdentifier.AnyUser, "apikey=test");
但由于我无法在AuthenticationOnValidateIdentity
的任何地方获取这些值,我想知道这是否可行。
因此,问题仍然存在:如何将附加信息传递给Azure Active Directory身份验证流程?