azure - 从 MVC 5(Azure AD) 访问 WebAPI 时,此请求的授权被拒绝
问题描述
因此,当我从 Azure AD 获取访问令牌时,我试图从 MVC 5 调用 WebAPI ToDoList,并且发送的令牌如下所示:request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", appToken)。但无论授权结果如何:- StatusCode : 401,改写:授权已被拒绝。但是,尽管在 NativeClientApp、.NET Core 中使用相同的授权,但我关注了 microsoft azure 文章和论坛,但没有成功。
请注意:WebAPI 项目和 MVC 项目在同一个解决方案中。
public async Task<string> GetTokenForApplication()
{
string signedInUserID =
ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
string tenantID =
ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID =
ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
// Get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
ClientCredential clientcred = new ClientCredential(clientId, appKey);
// Initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
return appToken = authenticationResult.AccessToken;
}
public async Task<ActionResult> Index()
{
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
//
try
{
Uri servicePointUri = new Uri(graphResourceID);
Uri serviceRoot = new Uri(servicePointUri, tenantID);
appToken = string.Empty;
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
async () => await GetTokenForApplication());
// Use the token for querying the graph to get the user details
var result = await activeDirectoryClient.Users
.Where(u => u.ObjectId.Equals(userObjectID))
.ExecuteAsync();
IUser user = result.CurrentPage.ToList().First();
List<TodoItem> itemList = new List<TodoItem>();
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, todoListBaseAddress + "api/todolist");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", appToken);
HttpResponseMessage response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>();
JsonSerializerSettings settings = new JsonSerializerSettings();
String responseString = await response.Content.ReadAsStringAsync();
responseElements = JsonConvert.DeserializeObject<List<Dictionary<String, String>>>(responseString, settings);
foreach (Dictionary<String, String> responseElement in responseElements)
{
TodoItem newItem = new TodoItem();
newItem.Title = responseElement["Title"];
newItem.Owner = responseElement["Owner"];
itemList.Add(newItem);
}
return View();
}
return View(user);
}
catch (AdalException ex)
{
ex.ToString();
// Return to error page.
return View("Error");
}
// If the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
catch (Exception ex)
{
ex.ToString();
return View("Relogin");
}
}
解决方案
推荐阅读
- c# - 计算一组成绩的最终平均值的程序
- android - 删除片段中的堆栈
- c++ - Qt:模拟来自顶级父小部件的 QMouseButtonPress 事件
- swift - 想要使用 Firebase 和 GeoFire 将用户配置文件加载到 tableView
- python - 对 github3.py 检索到的问题中的评论进行更快的迭代?
- azure-active-directory - 通过 Graph 为资源创建 OAuth2PermissionGrant
- spotfire - Tibco Spotfire webplayer,通过 url 设置文档属性
- python - 在回归模型中使用 gps 坐标的最佳方法是什么
- c# - 必须使用适当的属性或方法修改“接受”标头。参数名称:名称
- python - 如何清理熊猫数据框中的图像格式?