0

从我的MVC Web应用程序成功进行AD身份验证后,我在标头中设置了令牌,以便客​​户端脚本可以使用它访问Web API 。如何通过Azure AD身份验证令牌,以便AngularJS可以使用它们调用webapi

OnAuthorizationCodeReceived()后在成功登录

private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context) 
    { 
     var code = context.Code; 

     ClientCredential credential = new ClientCredential(clientId, appKey); 
     string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value; 
     AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectID)); 

     Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)); 

     AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, graphResourceId); 

     HttpContext.Current.Request.Headers.Add("Authorization", "Bearer " + result.AccessToken); 
    } 

在最后一行我设置 “授权” 报头。不过,我似乎无法利用AngularJS中的那个API来完成api调用!我在这里错过了什么?要求是我不必使用ADAL从AngularJS进行身份验证,因为Web应用程序已经对用户进行了身份验证并向我传递了有效令牌。

回答

1

你可以尝试保存在cookie中的访问令牌:

HttpCookie tokenCookies = new HttpCookie("token"); 
tokenCookies.Value = result.AccessToken; 
tokenCookies.Expires = DateTime.Now.AddHours(1);        
HttpContext.Current.Response.Cookies.Add(tokenCookies); 

然后在客户端进行Ajax调用访问令牌从饼干。

+0

从角度调用webapi只传递标头中的令牌不起作用。我认为应该有办法将接收到的令牌从客户端通过API传递回Azure并获得身份验证并获得身份验证? [link](https://azure.microsoft.com/nl-nl/resources/samples/active-directory-angularjs-singlepageapp-dotnet-webapi/)效果不错,因为它使用ADAL独立于网站进行身份验证。在我的情况下,身份验证发生在MVC Web应用程序中,并且角度只应使用令牌来调用API。任何有识之士都非常感谢! – user2058413

+0

我想我可能会走在正确的轨道上。因为我可以从AngularJS获得令牌给服务器端;我想我应该手动验证令牌。这[链接](https://github.com/Azure-Samples/active-directory-dotnet-webapi-manual-jwt-validation/blob/master/TodoListService-ManualJwt/Global.asax.cs)显示了一个自定义验证处理程序。在我的情况下,它在tokenHandler.ValidateToken()上引发异常。评论说“授权_uri”和“受众”缺失。我想我需要用这个标记发送这两个。我应该通过标题发送吗?如果是的话,我应该使用什么名字作为钥匙? – user2058413

+0

如果访问令牌在请求头中包含正确的权限.with访问令牌,您可以打电话给您自己的apis/microsoft托管apis(无论是在anjular应用程序还是像fiddler这样的工具)。 –

相关问题