Getting Logged-in userId in Salesforce Hybrid Mobile App

If you are building a Salesforce Hybrid Mobile Application and like me are having issues trying to find documentation on how to perform certain actions, this blog might help you out. The issue I was having was the lack of documentation around getting the current logged in userId after you were logged into the application.

I did some searching and was not very successful in finding the answer. None of the sample hybrid apps within the SDK displayed how to get the user information. So I started digging in the code. The most helpful place I found in the sample app was in the SalesforceOAuthPlugin.js file. Here there is a getAuthCredentials function which returns a Cordova dictionary of accessToken, refreshToken, clientId, userId, orgId, loginUrl, instanceUrl, and userAgent.

After seeing this, I was sure this is what I needed. The issue now was trying to find out where this was used within the sample application. If you look in the index.html file there is a function called onDeviceReady which initiates getAuthCredentials and registers an event listener that refreshes the SFDC session calling the salesforceSessionRefreshed function when completed.

So this is where the magic happens:

function salesforceSessionRefreshed(creds) {
var credsData = creds;
if( Event sets the `data` object with the auth data.
credsData =;
//Set the userId from credentials to a local variable
userId = credsData.userId;

Now we have userId instantiated with the current user’s Id. This is now available for any subsequent queries you may need to make that are unique to the current user.

I am not sure why there is not more documentation around this as this seems to be one of the things that anyone building a Salesforce Hybrid Mobile application would be using but there it is. Hopefully it helps you out and saves you some time from looking all over.

This entry was posted in Technology and tagged , , , , , . Bookmark the permalink.