我試圖做一個概念驗證。我正在使用Azure Active Directory並嘗試在傳統項目中實現OAuth。將持票人標記寫入Javascript
這個項目的一半是使用Web窗體,另一半是通過JavaScript直接在另一個項目中調用WebAPI。
作爲測試,我通過UseOpenIdConnectAuthentication的AuthorizationCodeReceived通知事件獲取承載令牌。我趕緊寫令牌正在調用與下面的代碼的WebAPI的頁面:
$.ajax({
url: baseVotingHeaderURL,
type: 'GET',
dataType: "json",
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Bearer ' + XXXXXXXXXXXXXXXXX);
},
success: function(result) {
options.success(result);
},
error: function(err) {
options.error(err);
}
});
我可以看到提琴手該令牌被傳遞:
沒有Proxy-Authorization頭是存在的。 授權頭存在:承載XXXXXXXXXXXXXXXX(我已經明顯取代與X的令牌)
我仍然得到一個未經授權的401
爲什麼不這項工作?
下面是Startup.Auth.cs
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = "XXXXXX.onmicrosoft.com",
AuthenticationType = "OAuth2Bearer",
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = "https://XXXX.onmicrosoft.com/XXXXX"
}
});
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
Authority = "https://login.microsoftonline.com/XXXXX.onmicrosoft.com",
PostLogoutRedirectUri = "https://XXXXXXX/gbl/Home.aspx",
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
},
AuthorizationCodeReceived = context =>
{
var client = ClientId;
var key = "XXXXXXXXXXXXXXXXXXX=";
var credential = new ClientCredential(client, key);
var authority = String.Format(CultureInfo.InvariantCulture, @"https://login.microsoftonline.com/{0}", "XXXXX.onmicrosoft.com");
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);
Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
var apiResourceId = "https://graph.windows.net";
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
context.Code, redirectUri, credential, apiResourceId);
EndpointAndTokenHelper.DecodeAndWrite(result.AccessToken);
System.Diagnostics.Debug.WriteLine(result.AccessToken);
return Task.FromResult(0);
}
}
});
}
這些示例使用圖形,因爲這是他們想要調用的API。 – vibronet
我認爲Graph是Azure AD中的另一個端點,用於查詢有關用戶的更多信息。 – Chris
它是 - 但正因如此,它是需要訪問令牌的資源:請求該令牌遵循適用於Azure AD保護的所有其他API的相同「物理定律」,並且包括指定資源標識 – vibronet