问题描述
Azure AD身份验证遇到一些问题。
我的应用程序体系结构是Asp.net MVC Web和Web API作为中间件
当我尝试通过MVC在Web API上使用AD令牌进行身份验证时,我无法从代码中的WEB API获得任何错误,甚至没有响应 但是,如果我尝试使用已经使用凭据对MVC应用进行身份验证的浏览器访问API,则效果很好。
下面是访问API的代码,但是没有用
AuthenticationResult result = null;
string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
string apiclientId = ConfigurationManager.AppSettings["ida:apiclientId"];
string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
string postlogoutRedirectUri = ConfigurationManager.AppSettings["ida:ApplicationURI"];
string postLoginRedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];
string authority = aadInstance + tenantId;
IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();
var account = await app.GetAccountAsync(ClaimsPrincipal.Current.GetMsalAccountId());
string[] scopes = { "openid profile offline_access email User.Read" };
try
{
// try to get an already cached token
result = await app.AcquiretokenSilent(scopes,account).ExecuteAsync().ConfigureAwait(false);
}
catch (MsalUirequiredException ex)
{
{
// A MsalUirequiredException happened on AcquiretokenSilentAsync.
// This indicates you need to call AcquiretokenAsync to acquire a token
//Debug.WriteLine($"MsalUirequiredException: {ex.Message}");
try
{
// Build the auth code request Uri
string authReqUrl = await OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes,app,this.HttpContext,Url);
}
catch (MsalException msalex)
{
Response.Write($"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
}
}
var handler = new httpclienthandler();
handler.ServerCertificateCustomValidationCallback = (sender,certificate,chain,sslPolicyErrors) => true;
handler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
HttpClient client = new HttpClient(handler);
//apiUrl client.BaseAddress = apiUrl;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,apiUrl + "api/General/GetUserDetailsByEmailAddress?emailAddress=ikhlesh.saxena@amexassetmanagement.com");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",result.Accesstoken);
try
{
HttpResponseMessage response = await client.SendAsync(request);
}
catch (Exception ex)
{
}
解决方法
检查您的范围是否允许您访问API。另外,您需要在API端调试令牌是否随请求一起发送,如果是,则如何对其进行验证。