Authenticate

Overview

You authenticate to a web service, using a bearer token. This article explains how to obtain a bearer token, using JavaScript.

PREREQUISITES: Before you request a token, you must configure the authentication settings.
For more information, see Request access token » Default authentication protocol settings.

Request a bearer token with the Default protocol

Following is a sample function that will authenticate you in Sitefinity CMS. The function works in the following way:

  1. It sends a POST request to the server.
  2. If successful, the server return a bearer token.
  3. The token is saved in the sitefinity object.
  4. The object is passed in the function allowing access to the OData web services.

Use the following sample:

JavaScript
function loginDefaultAuth(sitefinity, sitefinityUrl, username, password) {
   var url = sitefinityUrl + "/sitefinity/oauth/token";
   var data = {
       username: username,
       password: password,
       grant_type: "password",
       client_id: "testApp",
       client_secret: "secret"
   };

   var body = "";
   Object.keys(data).forEach(key => {
       if (body.length) {
           body += "&";
       }
       body += key + "=";
       body += encodeURIComponent(data[key]);
   });

   var xhr = new XMLHttpRequest();

   xhr.open("POST", url, true);
   xhr.addEventListener("load", () => {
       if (xhr.status == 200) {
           let token = JSON.parse(xhr.responseText);

           let tokenObj = {
               type: token.token_type,
               value: token.access_token
           };

           sitefinity.authentication.setToken(tokenObj);
       }
   });

   xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

   xhr.send(body);
}
Want to learn more?
Enhance your Sitefinity skills by enrolling in free training sessions. Become Sitefinity certified through Progress Education Community to strengthen your professional credentials.