Registering and configuring a SPA application with adal.js

Registering and configuring a SPA application with adal.js

Walkthrough:

https://docs.microsoft.com/zh-cn/powerapps/developer/common-data-service/walkthrough-registering-configuring-simplespa-application-adal-js

Practice:

https://tools.211cn.ca/try/d365-spa.html

Environment:

Site: ALADDIN GO

https://aladdingo.crm3.dynamics.com/

dev@aladdingoo.onmicrosoft.com

Azure: https://portal.azure.com

Application:

sample app

Key Points

Auth

// Function that manages authentication
function authenticate() {
    //OAuth context  
    authContext = new AuthenticationContext(config);

    // Check For & Handle Redirect From AAD After Login  
    var isCallback = authContext.isCallback(window.location.hash);
    if (isCallback) {
        authContext.handleWindowCallback();
    }  
    var loginError = authContext.getLoginError();

    if (isCallback && !loginError) {
        window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
    }
    else {
        errorMessage.textContent = loginError;
    }
    user = authContext.getCachedUser();
}

function login() {
    authContext.login();
}

//function that logs out the user
function logout() {
    authContext.logOut();
    accountsTable.style.display = "none";
    accountsTableBody.innerHTML = "";
}

Get Accounts

var req = new XMLHttpRequest()
req.open("GET", encodeURI(organizationURI + "/api/data/v9.1/accounts?$select=name,address1_city&$top=10"), true);
//https://aladdingo.crm3.dynamics.com/api/data/v9.1/accounts?$select=name,address1_city&$top=10
//Set Bearer token
req.setRequestHeader("Authorization", "Bearer " + token);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
  req.onreadystatechange = null;
  if (this.status == 200) {
    var accounts = JSON.parse(this.response).value;
    renderAccounts(accounts);
  }
  else {
    var error = JSON.parse(this.response).error;
    console.log(error.message);
    errorMessage.textContent = error.message;
  }
}
};
req.send();

Issues encountered

1. AADSTS700054: response_type ‘id_token’ is not enabled for the application.

Solution:

enable ID Token
set oauth2AllowImplicitFlow = false


2. AADSTS500111: The reply uri specified in the request has an invalid scheme.

Solution: enter correct url

3. AADSTS65001: The user or administrator has not consented to use the application with ID ‘015de0c1-8…’

Solution: grant consent

Success

OData result

https://aladdingo.crm3.dynamics.com/api/data/v9.1/accounts
https://aladdingo.crm3.dynamics.com/api/data/v9.1/accounts?$select=name,address1_city&$top=10

Source code

 660 total views

Author: Albert

Leave a Reply