I want Access token in sharepoint Hosted addin in order to consume Microsoft Graph Api. When I hit Access Token Api (https://login.microsoftonline.com/dimensiondata2.onmicrosoft.com/oauth2/token) using Postman I am able to get access token, But using code, I am getting 401 unauthorized error. I refer this Documentation
Following is the error:-[
{
"SchemaVersion":"15.0.0.0","LibraryVersion":"16.0.8412.1210","ErrorInfo":null,"TraceCorrelationId":"7e4eb29e-c011-0000-1892-c2fb5c7aa49d"
},2,{
"_ObjectType_":"SP.WebResponseInfo","Body":"The remote server returned the following error while establishing a connection - 'Unauthorized'.","Headers":null,"StatusCode":401
}
]
This is How i created Request object:-
var context = SP.ClientContext.get_current();
var request = new SP.WebRequestInfo();
var body = "client_id=" + client_id + "&client_secret=" + client_secret + "&resource=" + resource + "&grant_type=" + grant;
request.set_url(
"https://login.microsoftonline.com/companyname.onmicrosoft.com/oauth2/token"
);
// We need the response formatted as JSON.
request.set_headers({"Content-Type": "application/x-www-form-urlencoded" });
request.set_method("POST");
request.set_body(body);
var response = SP.WebProxy.invoke(context, request);
In my AppManifest.xml I have added following EndPoint:-
<RemoteEndpoints>
<RemoteEndpoint Url="https://login.microsoftonline.com/domainname.onmicrosoft.com/oauth2/token" />
</RemoteEndpoints>