我正在谈论的场景是本地调试场景,因为我还没有部署到azure。
我有一个针对AAD进行身份验证的MVC Web App,它调用了WebAPI 我在AAD租户中设置了正确的权限,我说它设置正确是因为我能够为WebAPI获取AccessToken,但是当我尝试调用WebAPI时它会给我以下错误
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Pragma: no-cache
X-SourceFiles: =?UTF-8?B?xxxxxxxxxx
Cache-Control: no-cache
Date: Sun, 27 Mar 2016 02:06:31 GMT
Server: Microsoft-IIS/10.0
WWW-Authenticate: Bearer
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 61
Content-Type: application/json; charset=utf-8
Expires: -1
}}
代码
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
NaiveSessionCache nsc = new NaiveSessionCache(userObjectID);
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, nsc);
ClientCredential credential = new ClientCredential(clientId, appKey);
result = authContext.AcquireTokenSilent(todoListClientId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
Uri webApiUri = new Uri(string.Format("{0}{1}", todoListBaseAddress, "/api/TodoList"));
string accessTknString = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(result.AccessToken));
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, webApiUri);
request.Headers.Add(System.Net.HttpRequestHeader.Authorization.ToString(), string.Format("Bearer {0}", accessTknString));
HttpResponseMessage response = await client.SendAsync(request);