我目前正在为Outlook开发一个应用程序。我有一个Javascript插件项目和一个MVC Web API项目。我正在尝试将令牌从插件发送到API,并从所述令牌中获取一个新的令牌来访问Sharepoint和Exchange。
目前我得到以下错误:
AADSTS70002:验证凭据时出错。AADSTS50013:断言受众声明与所需值不匹配。
以下是我如何从Javascript插件中获取令牌:
//GET NEW ACCESS TOKEN
var _mailBox = Office.context.mailbox;
_mailbox.getUserIdentityTokenAsync(function (result) {
var token = result.value;
var item = _mailbox.item;
//The initial ajax to the Web API
$.ajax({
type: 'POST',
url: "https://192.168.0.150:30303/api/api/uploadfile";
data: JSON.stringify({
'MailId': item.itemId,
'SpListguid': guid //GUID of the Sharepoint list we wish to upload this email to
}),
headers: {
'Authorization': 'Bearer ' + token,
},
contentType: 'application/json'
}).done(function () {
console.log("Successfully hit the service");
}).error(function (err) {
console.log("Something went wrong! Oh boi!");
console.log(err);
})
})
下面是我如何在我的MVC Web API中处理令牌:
[EnableCors(origins: "*", headers"Origin, Content-Type, Authorization, Accept", methods: "GET, POST, OPTIONS")]
public class APIController : ApiController
{
[HttpPost]
public IHttpActionTResult UploadFile(){
using(ClientContext clientcontext = SharePointHelper.GeClientContextWithAccessToken(this.ControllerContext))
{
//Do something once done
}
}
}
这是SharePointHelper
类,方法为GetClientContextWithAccessToken(HttpControllerContext)
:
public class SharepointHelper
{
public static Clientcontext GetclientcontextwithAccessToken(HttpControllercontext controlerContext)
{
string tenantId = {my-tenant-id};
string authority = string.format("https://login.windows.net/{0}", tenantId);
string resource = {the-app-id-uri-from-my-addin-in-azure}; //example could be "https://sharepointcommunity.com/outlookaddin"
AuthenticationContext authContext = new AuthenticationContext(authority)
var authResult = AcquireUserAssertionAccessToken(controllerContext, authContext, resource)
}
private static AuthenticationResult AcquireUserAssertionAccessToken(HttpControllercontext controllercontext, AuthenticationCotnext authContext, string resource)
{
var rawToken = controllerContext.Request.Headers.GetValues("Authorization").First();
string userAccessToken = token.Substring(token.LastIndexOf(' ')).Trim(); //To remove the "Bearer"
var cc = new ClientCredentials({my-client-id}, {my-client-secret});
var ua = new UserAssertion(userAccessToken);
var result = authContext.AcquireToken(resource, cc, ua);
}
}
最后一行是发生错误的地方(var result = ...
)。
我不确定发生这种情况是因为JavaScript插件中的错误标识令牌,还是其他原因。
注意:AAD中的JavaScript插件具有访问AAD中MVC Web API的权限。MCV Web API具有访问Exchange和SharePoint的权限。
前提是我不知道办公室的人在他们的包装方法中到底做了什么。
-
您应该在服务器端请求的资源不是您的addin,但sharepoint或exchange。让API请求令牌因为前端没有任何我能想到的用途。如果你把它修好了,它仍然不起作用。
-
尝试使用构建
UserAssertion
string userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
UserAssertion userAssertion = new UserAssertion(userAccessToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);