var variables = {
//
Domain of Azure AD tenant
azureAD: "orgname.onmicrosoft.com",
//
ClientId of Azure AD application principal
clientId: "11111111-1111-1111-1111-111111111111",
resource:
= location.hostname == "localhost"
? "ms crm root url"
: location.origin;
}
window.config = {
tenant: variables.azureAD,
clientId: variables.clientId,
postLogoutRedirectUri: window.location.origin,
endpoints:
{ orgUri: variables.resource },
cacheLocation: "localStorage"
};
var authContext = new
AuthenticationContext(config);
After the authentication context is
created, we make sure the user is authenticated.
var user = authContext.getCachedUser();
if (!user) {
authContext.login();
}
Now login to application
var token;
var token;
if (user) {
authContext.acquireToken(variables.resource,
(message, token) => {
if
(token) {
token
= token;
}
else {
authContext.login();
}
});
}
else {
authContext.login();
}
jQuery API call
var baseUrl = ' root url ';
var url = '/actionname';
$.ajax({
type: "GET",
url: baseUrl + url,
headers: {
"Authorization":
"Bearer " + token,
"accept":
"application/json;odata=verbose"
}
}).done(function
(response) {
console.log("Successfully
fetched list.");
var
items = response.d.results;
}).fail(function
() {
console.log("Fetching
list from SharePoint failed.");
});
Using Typescript Core JS API Call of MS
CRM Rest
let baseUrl = 'root url';
let url = '/actionname';
let
body = {
<parameter name>: < parameter
name value> || ""
}
let method = “GET”
public restapiCall(baseUrl , url, method, token,
body): Promise<any>
{
var
headers: any = {
"Accept":
"application/json; odata.metadata=none",
"Content-Type":
"application/json",
"Cache-Control":
"no-cache, no-store"
//Dont cache values; had an issue that acc status was
not updated as and when it changes in CRM.
};
if
(token) { headers["Authorization"]
= "Bearer " + token; }
let
parser: any = function
(res: Response) {
if
(res.status == 204) {//No data
return
{ value: [], headers: res.headers, status: res.status }
} else
{
return
res.json().then((jsonParsed) => {
if
(!res.ok) throw new
Error(jsonParsed.error.message);
jsonParsed["headers"] = res.headers;
jsonParsed["status"] = res.status;
return
jsonParsed;
});
}
}
return
fetch((url.indexOf("http")
== 0 ? url : baseUrl + url), {
credentials: 'same-origin',
headers: headers,
method: method,
body: typeof
body == "string" ? body :
JSON.stringify(body)
}).then(parser);
}