asp.net-mvc - 来自 MVC 的授权 Web API 访问
问题描述
我在 Azure AD 身份验证方面遇到了一些问题。
我的应用程序架构是 Asp.net MVC Web & Web API 作为中间件
当我尝试使用来自 MVC 的 Web API 上的 AD 令牌进行身份验证时,我无法在代码中收到任何错误,甚至没有来自 WEB API 的响应但是如果我尝试使用浏览器访问 API,而我已经使用了凭据进行身份验证MVC 应用程序运行良好。
下面是访问 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 端调试令牌是否随请求一起提供,如果是,则如何验证。
推荐阅读
- c# - 发送带有 Outlook 提醒的电子邮件
- python - 如何在需要使用元素树解析的文件名中使用通配符
- php - 删除 laravel 视图文件中值的重复条目
- python - Python请求不更新get的标头
- python - 哪个 requirements.txt 相当于在 pip 上使用`-f url`?
- mapbox - 如何检测地图视图mapbox iOS SDK上的单击
- php - lumen,怎么不能显示同名?
- amazon-web-services - Step Functions 调用部署在 ECS 中的 Fargate 服务的操作/API
- php - CyberPanel 中 WordPress 站点建立数据库连接时出错
- python - Python df.to_sql 导致挂起和暂停