web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Authenticate the Request for get Token using XmlHttpRequest

(0) ShareShare
ReportReport
Posted on by

Hi ,

Please help me out !!

I am using XmlHttpRequest for Authentication ,

Problem:- On-Page Load , I want to get the Token from Your application token endpoint. I paste the code below . This code not showing any error and not give any token.

Please review the code and tell me What i am doing wrong.

_______________________________________

    Var key;

    var token_ // variable will store the token
    var clientID = "ABCD"; // app clientID
    var clientSecret = "XYZABC"; // app clientSecret
    var url = "abczx.azurewebsites.net/.../token"; // Your application token endpoint  
    var request = new XMLHttpRequest();
    var params = 'grant_type=client_credentials&client_id=' + clientID + '&client_secret=' + clientSecret +    '&scope=serviceapi';
   request.open("POST", url, false);
    
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  
    request.setRequestHeader("Accept", "application/json");
    request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
   
    request.onreadystatechange = function ()

{
        if (request.readyState == 4 && request.status == 200)
        {
            var response = JSON.parse(request.responseText);
            alert(response);
            var obj = JSON.parse(response);
            key = obj.access_token; //store the value of the accesstoken
            token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
        }
    }
    request.send(params);

_______________________________________

*This post is locked for comments

I have the same question (0)
  • Community Member Profile Picture
    on at

    Hi Guys please help me out.

  • Community Member Profile Picture
    on at

    Any Example for ms crm 2016 online Web API with authentication. Using XmlHttpRequest  through java-script

  • Community Member Profile Picture
    on at

    Hi Pankaj,

    Did you find any Sample Code? am also looking like same your request.

  • Suggested answer
    Community Member Profile Picture
    on at

    hi Shiva,

    1. You need to change in your AuthServer config file which provied you Token

    ex.  <system.webServer>

       <modules runAllManagedModulesForAllRequests="true"/>

     <httpProtocol>

     <customHeaders>

     <add name="Access-Control-Allow-Origin" value="*" />

     <add name="Access-Control-Allow-Headers" value="Origin, X-

                               Requested-With, Content-Type, Accept,Authorization" />

     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT,

                               DELETE, OPTIONS" />

     </customHeaders>

     </httpProtocol>

     </system.webServer>

    2. I am using javascript file for CRM . Code working on addOnKeyPress fuction .

    ex. //||***** This function fire addOnKeyPress of address1_city Text box. This is the auto complete ******* ||

    "use strict";

    Xrm.Page.getControl("address1_composite_compositionLinkControl_address1_city").addOnKeyPress(function (ext) {

       var response;

       var CountryCode = null;

       var StateCode = null;

       var PCode = null;

       var userEmail;

       var NotificationID;

       var NotificationMessage;

       var FirstName;

       var LastName;

       var xhttp = new XMLHttpRequest();

       //This is Qrganization UniqueCode Like:- orgc9f08190

       var OrganizationCodeName = Xrm.Page.context.getOrgUniqueName();

       //This is the Client login URl

       var clientUrl = Xrm.Page.context.getClientUrl();

       //This is the host Api Url

       var apiUrl = "[View:https://XYZ.azurewebsites.net/api/CRM/GetCRMData:750:50]";

       //*************** Start ---- Get the user Information ----- **********************//

       var ODataPath = clientUrl + "/XRMServices/2011/OrganizationData.svc";

       var userRequest = new XMLHttpRequest();

       userRequest.open("GET", ODataPath + "/SystemUserSet(guid'" + Xrm.Page.context.getUserId() + "')", false);

       userRequest.setRequestHeader("Accept", "application/json");

       userRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");

       userRequest.send();

       if (userRequest.status === 200) {

           var retrievedUser = JSON.parse(userRequest.responseText).d;

           //This is the Current user Email ID

           userEmail = retrievedUser.InternalEMailAddress;

           FirstName = retrievedUser.FirstName;

           LastName = retrievedUser.LastName;

       }

       //*************** END ---- Get the user Information--- ***********************************//

       if (Xrm.Page.getAttribute("address1_country").getValue() !== null) {

           CountryCode = Xrm.Page.getAttribute("address1_country").getValue();

       }

       if (Xrm.Page.getAttribute("address1_stateorprovince").getValue() !== null) {

           StateCode = Xrm.Page.getAttribute("address1_stateorprovince").getValue();

       }

       var CityCode = Xrm.Page.getControl("address1_composite_compositionLinkControl_address1_city").getValue();

       if (Xrm.Page.getAttribute("address1_postalcode").getValue() !== null) {

           PCode = Xrm.Page.getAttribute("address1_postalcode").getValue();

       }

       if (CityCode.length >= 2) {      

           var params = "CountryCRM=" + CountryCode + "&StateCRM=" + StateCode +

                    "&CityCRM=" + CityCode + "&PostalCodeCRM=" + PCode + "&flag=3" + "&OrganizationUrl=" + clientUrl + "&OrganizationUniqueName=" + OrganizationCodeName + "&UserEmail=" + userEmail + "&UserFirstName=" + FirstName + "&UserLastName=" + LastName;

           xhttp.open("POST", apiUrl, true);

           xhttp.setRequestHeader("Accept", "application/json");

           xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

           xhttp.send(params);

           xhttp.onreadystatechange = function ()

           {

               //Call a function when the state changes.

               if (xhttp.readyState === 4 && xhttp.status === 200) {

                   response = JSON.parse(xhttp.responseText);

                   var resultSet =

                          {

                              results: new Array(),

                              commands:

                                  {

                                      id: "City",

                                      label: "New",

                                      action: function () {

                                          window.open(clientUrl);

                                      }

                                  }

                          };

                   var userInputLowerCase = CityCode.toLowerCase();

                   for (var i = 0; i < response.length; i++) {                  

                       resultSet.results.push({

                           id: i,

                           fields: [response[i].NameCRM, ]

                       });

                       if (resultSet.results.length >= response.length) {

                           break;

                       }

                   }

                   if (resultSet.results.length > 0) {

                       ext.getEventSource().showAutoComplete(resultSet);

                   }

                   else {

                       ext.getEventSource().hideAutoComplete();

                   }

               }

           }

       }

    });

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans