Get Current User Id Using REST API In SharePoint

 Given below are the steps to get Current User Id.

  1. Create SharePoint Hosted App project.
  2. Write code to get the Current User Id in App.js file.

Here, we are going to display user id in alert message. Based on your project requirement, you can use this User Id value in your project.

Step 1 - Create SharePoint Hosted App project.








  • Set scope of the Site Collection and set permissions as "FullControl".


Step 2 - Write the code to get current User Id in App.js file.

Open the App.js file, remove the existing code, and paste the below code.

  1. 'use strict';  
  2. var hostweburl;  
  3. var appweburl;  
  4. var context = SP.ClientContext.get_current();  
  5. var user = context.get_web().get_currentUser();  
  6. // This code runs when the DOM is ready and creates a context object which is   
  7. // needed to use the SharePoint object model   
  8. $(document).ready(function() {  
  9.     //Get the URI decoded URLs.   
  10.     hostweburl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));  
  11.     appweburl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));  
  12.     var scriptbase = hostweburl + "/_layouts/15/";  
  13.     getCurrentUserREST();  
  14. });  
  15. // Retrieve a query string value.   
  16. function getQueryStringParameter(paramToRetrieve) {  
  17.     var params = document.URL.split("?")[1].split("&");  
  18.     for (var i = 0; i < params.length; i = i + 1) {  
  19.         var singleParam = params[i].split("=");  
  20.         if (singleParam[0] == paramToRetrieve) return singleParam[1];  
  21.     }  
  22. }  
  23.   
  24. function getCurrentUserREST() {  
  25.     $.ajax({  
  26.         url: appweburl + "/_api/web/currentUser",  
  27.         method: "GET",  
  28.         headers: {  
  29.             "Accept""application/json; odata=verbose"  
  30.         },  
  31.         success: function(data) {  
  32.             var UserId = data.d.Id; //Assigning UserId Variable  
  33.             alert("Current User Id= " + UserId);  
  34.         },  
  35.         error: function(data) {}  
  36.     });  
  37. }  

 


  • After "Trusting" the app, it will display the current User Id in alert message, whenever the page is reloaded.


That's it. Please send your feedback in comments section.