因此,我试图从MVC 5调用WebAPI ToDoList,同时从Azure AD获取访问令牌,并且令牌的发送方式如下:request.Headers.Authorization = new AuthenticationHeaderValue(“ Bearer”,appToken )。但是无论授权结果是什么:- 状态码: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");
}
}