我正在致力于将 Web Api 与 azure China Active Directory 集成并部署到 azure China 环境。 Azure 中国的端点与常规 Azure 环境完全不同。我想知道如何指定AADInstance https://login.chinacloudapi.cn/用于 Web API?
Web Api Startup.Auth.cs
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
},
});
Web Api Web.Config
<add key="ida:Tenant" value="directoryname.partner.onmschina.cn" />
<add key="ida:Audience" value="https://directoryname.partner.onmschina.cn/AppName" />
<add key="ida:ClientID" value="…" />
<add key="ida:Password" value="…" />
这可以针对 MVC 应用程序完成
MVC Startup.Auth.cs
ApplicationDbContext db = new ApplicationDbContext();
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
return Task.FromResult(0);
}
}
});
MVC Web.Config
<add key="ida:ClientId" value="…" />
<add key="ida:AADInstance" value="https://login.chinacloudapi.cn/" />
<add key="ida:ClientSecret" value="…" />
<add key="ida:Domain" value="directoryname.partner.onmschina.cn" />
<add key="ida:TenantId" value="…" />
<add key="ida:PostLogoutRedirectUri" value="https://localhost:44300/" />
是的,我们必须设置元数据端点。如 WindowsAzureActiveDirectoryBearerAuthenticationExtensions.cs 中所述
我在 web.config 中添加了一个条目
<add key="ida:AADInstance" value="login.microsoftonline.com" />
然后在Startup.Auth.cs中设置MetadataAddress
MetadataAddress = $"https://{ConfigurationManager.AppSettings["ida:AADInstance"]}/{ConfigurationManager.AppSettings["ida:Tenant"]}/federationmetadata/2007-06/federationmetadata.xml".
现在可以了。
我是一名优秀的程序员,十分优秀!