Print This Post

WSS 3.0: getting the current user login name via javascript

Updated 06 September 2008 - see the end of the post for details of how to get further user properties by using the user profile web service

This is just a quick post in response to a question I’ve had about how to get the current user’s login details in WSS 3.0. The answer is really in two parts. Firstly, you can get the ID of the current user from the _spUserId variable which is declared by the welcome control on any page.

To test this type javascript:alert(_spUserId) in the browser address bar whilst on a SharePoint page:

Now that we’ve got the internal ID of the user we can look them up in the hidden User Information List. This list contains basic information about users and their profile properties and can be searched using the Lists.asmx web service. The following example uses the javascript API that I published previously to get the user name for user ID 1:

var lists = new SPAPI_Lists('')
var items = lists.getListItems(
'User Information List',
'',
'<Query><Where><Eq><FieldRef Name="ID"/><Value Type="Counter">1</Value></Eq></Where></Query>',  // query
'<ViewFields><FieldRef Name="Name"/></ViewFields>',
1,  // rowLimit
''  // queryOptions
);

if (items.status == 200)
{
    var rows = items.responseXML.getElementsByTagName('z:row');

    if (rows.length == 1)
    {
        alert('The user name is: ' + rows[0].getAttribute('ows_Name'));
    }
    else
    {
        alert('No user was found');
    }
}
else
{
    alert('There was an error: ' + items.statusText);
}

We can wrap this all up into a neat little function which returns the login name based on an ID. Note that the returned login name will depend on the authentication provider. It might be an Active Directory login, a forms authentication user name, or something custom.

function getCurrentUserName()
{
    var lists = new SPAPI_Lists('')
    var items = lists.getListItems(
    'User Information List',
    '',
    '<Query><Where><Eq><FieldRef Name="ID"/><Value Type="Counter">' + _spUserId + '</Value></Eq></Where></Query>',  // query
    '<ViewFields><FieldRef Name="Name"/></ViewFields>',
    1,  // rowLimit
    ''  // queryOptions
    );

    if (items.status == 200)
    {
        var rows = items.responseXML.getElementsByTagName('z:row');

        if (rows.length == 1)
        {
            return rows[0].getAttribute('ows_Name');
        }
        else
        {
            return null;
        }
    }
    else
    {
        return null;
    }
} 

// Test code
var userName = getCurrentUserName();

if (userName != null)
{
    alert(userName);
}

Update: 06 September 2008 - javascript API 1.0.1

I’ve now updated the javascript API to version 1.0.1. This now includes support for the user profile web service via the SPAPI_UserProfile.js library. The user profile service provides a number of mechanisms for viewing and updating user profiles. Of particular interest is the getUserProfileByName method which returns the user profile of a user based on their login name. An example packet is shown below:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetUserProfileByIndexResponse xmlns="http://microsoft.com/webservices/SharePointPortalServer/UserProfileService">
      <GetUserProfileByIndexResult>
        <NextValue>2</NextValue>
        <UserProfile>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>UserProfile_GUID</Name>
            <Privacy>Public</Privacy>
            <Values>
              <ValueData>
                <Value xmlns:q1="http://microsoft.com/wsdl/types/" xsi:type="q1:guid">35c7e6d2-89fe-4cc2-9dc6-1f0803d3778c</Value>
              </ValueData>
            </Values>
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>AccountName</Name>
            <Privacy>Public</Privacy>
            <Values>
              <ValueData>
                <Value xsi:type="xsd:string">GLASGOW\Administrator</Value>
              </ValueData>
            </Values>
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>FirstName</Name>
            <Privacy>Public</Privacy>
            <Values>
              <ValueData>
                <Value xsi:type="xsd:string">Darren</Value>
              </ValueData>
            </Values>
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>LastName</Name>
            <Privacy>Public</Privacy>
            <Values>
              <ValueData>
                <Value xsi:type="xsd:string">Johnstone</Value>
              </ValueData>
            </Values>
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>PreferredName</Name>
            <Privacy>Public</Privacy>
            <Values>
              <ValueData>
                <Value xsi:type="xsd:string">Darren Johnstone</Value>
              </ValueData>
            </Values>
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>WorkPhone</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>Office</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>Department</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>Title</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>Manager</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>AboutMe</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>PersonalSpace</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>PictureURL</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>UserName</Name>
            <Privacy>Public</Privacy>
            <Values>
              <ValueData>
                <Value xsi:type="xsd:string">Administrator</Value>
              </ValueData>
            </Values>
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>QuickLinks</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>WebSite</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>PublicSiteRedirect</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-Dotted-line</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-Peers</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-Responsibility</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-Skills</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-PastProjects</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-Interests</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-School</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-SipAddress</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-Birthday</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-MySiteUpgrade</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-DontSuggestList</Name>
            <Privacy>Private</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-ProxyAddresses</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-HireDate</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-LastColleagueAdded</Name>
            <Privacy>Private</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-OWAUrl</Name>
            <Privacy>Private</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-ResourceAccountName</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>SPS-MasterAccountName</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>Assistant</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>WorkEmail</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>CellPhone</Name>
            <Privacy>Contacts</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>Fax</Name>
            <Privacy>Public</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>HomePhone</Name>
            <Privacy>Contacts</Privacy>
            <Values />
          </PropertyData>
          <PropertyData>
            <IsPrivacyChanged>false</IsPrivacyChanged>
            <IsValueChanged>false</IsValueChanged>
            <Name>EmployeeID</Name>
            <Privacy>Private</Privacy>
            <Values />
          </PropertyData>
        </UserProfile>
        <Colleagues />
        <QuickLinks />
        <PinnedLinks />
        <Memberships>
          <MembershipData>
            <Source>SharePointSite</Source>
            <MemberGroup>
              <SourceInternal>8bb1220f-de8b-4771-ac3a-0551242cf2bd</SourceInternal>
              <SourceReference>873FA19B-402A-444E-AD9B-E61984DB7AA7</SourceReference>
            </MemberGroup>
            <Group>SharePoint Sites</Group>
            <DisplayName>Admin</DisplayName>
            <Privacy>Public</Privacy>
            <MailNickname>nickname</MailNickname>
            <Url></Url>
            <ID>2</ID>
            <MemberGroupID>215</MemberGroupID>
          </MembershipData>
        </Memberships>
      </GetUserProfileByIndexResult>
    </GetUserProfileByIndexResponse>
  </soap:Body>
</soap:Envelope>

This can be used to access other profile properties (such as their preferred name and employee ID) for the user (once their login name is known). The following code requires that SPAPI_Core.js and SPAPI_UserProfile.js be included.

function getUserProfile(accountName)
{
    var profile = new SPAPI_UserProfile('')
    var p = profile.getUserProfileByName(accountName);

    if (p.status == 200)
    {
        return p;
    }
    else
    {
        return null;
    }
}

// Test code
var profileData = getUserProfile(getCurrentUserName()); // Custom GetCurrentUserName function

if (profileData != null)
{
    var properties = profileData.responseXML.getElementsByTagName('PropertyData');
    var propertyValues = new Array();

    for (var i=0; i<properties.length; i++)
    {
        var propName = properties[i].getElementsByTagName('Name')[0].childNodes[0].nodeValue;
        propertyValues[propName] = properties[i].getElementsByTagName('Value');
    }

    alert(propertyValues['AccountName'][0].childNodes[0].nodeValue);
    alert(propertyValues['EmployeeID'][0].childNodes[0].nodeValue);
}

The javascript above uses our original function to get the user name. It then calls the getUserProfileByName method of the user profile service to get the user profile XML. The XML is then parsed to create a hash table of XML nodes keyed by the property name. Note that a property may have more than one value so the hash table stores arrays of these values.

So to get the user’s login name we use:

propertyValues['AccountName'][0].childNodes[0].nodeValue;

…and for the employee ID…

propertyValues['EmployeeID'][0].childNodes[0].nodeValue;

There are many more methods made available by the profile service- I’ll post some examples soon.

There Are 16 Responses So Far. »

  1. hi Darren,
    do we need any package or any specific class definition file require to run this above script?
    i try running in my local browser, its raising an error at SPAPI_Lists(”) –> class not found error!
    or we should run this script only in sharepoint designer?

    -Vivek

  2. Hi Vivek,

    As I said in the post, you need to use the cross broswer javascript library located here http://darrenjohnstone.net/2008/07/22/a-cross-browser-javascript-api-for-the-sharepoint-and-office-live-web-services/.

    What I maybe didn’t say (and should have) is that from this library you need to import the following javascript files:


    JSAPI_Core.js
    JSAPI_Lists.js

    Also look here for other examples of things you might find useful: http://darrenjohnstone.net/2008/07/22/examples-for-the-sharepoint-and-office-live-javascript-api/.

    Cheers,
    Darren

  3. hi Darren,
    i tried your code in a share point site;
    (i remotely log in to the server and added your script in my master page since we have to run the javascript in master page, i did in the server;)
    it alerts me like “SharepointServer\Administrator”;

    when i access the same page in my system, i.e; client side, the alert is not coming! i couldn’t understand why! do you?

  4. Hi Vivek,

    If the alert is not shown then no value is being returned from the User Information List.

    Try typing javascript:alert(_spUserId) in the browser address bar? Did that work? Try getting the responseText property of the items object and see what that says.

    Why not try running IE on the server as yourself (right click and choose run as…) to see if the the same problem occurs.

    It might be that your own user account doesn’t have an entry in the User Information List. An entry is created for users when they are granted access to the site. To see if your user account has been added navigate to http://your_server_name/_catalogs/users/simple.aspx. This page will show a list of all users in the User Information List. There should be an entry with an ID (hover the mouse over the title column and look at the URL to see the ID) which matches the _spUserId variable.

    Cheers,
    Darren

  5. Hi Darren,
    Very impressive post! I am attempting to pull an employee ID attribute from the User Profile Store. I successfuly mapped the attribute from the Active Directory into MOSS, now I just need to be able to retrieve it and use it in a function. Once mapped, is the user attribute automatically populated to the User Information List? Also, where do you recommend I store the two JS files (JSAPI_Core.js and JSAPI_Lists.js), the 12 hive, or elsewhere. Thank you for your help in advance.

    Regards,
    Izzo

  6. Hi Izzo,

    Firstly, I don’t think that custom user profile properties will be stored in the User Information List. This list only stores basic properties.

    However, I’ve just uploaded v1.0.1 of the API which inclues a proxy for the user profile web service. This can be used to get the extra properties once the user name is known. I’ve updated the post to show you how to do this.

    I usually keep the .js files in the 12 hive: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\JSAPI.

    Cheers,
    Darren

  7. Hi Darren,

    First of all I would like to thank you on your post and a recent example. I have the functions implemented, however now I am getting an error that states “_spUserId is undefined”. Am I missing a declaration?
    Also, does it make any difference when referrencing SPAPI javascript files in a master page vs. aspx page? Thank you in advance.

    Regards,

    Izzo

  8. Hi Izzo,

    _spUserId is defined by the welcome control. It makes no difference if you include the javascript from the master page or your page template- just make sure that the welcome control is present.

    I tested this just now by pasting the following script into a content editor web part on a blank WSS site- it worked fine:


    <script language="javascript">
    alert(_spUserId);
    </script>

    View the source of your page and search for _spUserId. It is declared inline by the welcome control. If you don’t find it then check for the welcome control in your master page- it looks like this:


    <wssuc:Welcome id="IdWelcome" runat="server" EnableViewState="false">
    </wssuc:Welcome>

    If you have removed the welcome control for some reason then consider adding it back in but placing it in a hidden div.

    If the welcome control is present and you also find _spUserId in your page source then your problem might be due to the order of execution of the scripts. Try using the _spBodyOnLoadFunctionNames array to have your function execute on page load after the page has rendered:


    <script type="text/javascript">
    _spBodyOnLoadFunctionNames.push("YourFunctionName");
    </script>

    Cheers,
    Darren

  9. Hi Darren,

    It was totally my mistake. I was using a blank ASPX page with no layout attached nor master page. No wonder it never found _spUserId. Now I got everything working the way it should. Your post helped immensely. Thank you once again.

    Regards,

    Izzo

  10. Hi Darren ,

    Awsome work. :-)

    for one user it is working fine.but when I am click sign in as diffrent user all alert and display name it is not working …

    What is reason behind this.

    for example when i am trying with user DomainName\Pritesh it is working fine but when i am trying to change user and enter DomainName\Abhi then it will not display even alert of _spUserId…

    Thanks in Advance

    Pritesh Gandhi.

  11. Hey Darren,

    Can ya help me how can i get the Users Group Name?

    Thanx in Advance

  12. Hi,

    Really great library of code!

    Have problem with this one and wondering if you could shed some light on it.

    Receiving an error in the responseXml:

    Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).

    Thanks for sharing your work on this!

  13. For anyone else receiving the “Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)” error, I’ve spent some time looking into it and finally found a solution.

    It seems Darren’s getListItems() call here works as long as you use an account with Administrator status for your site collection, but any other accounts will receive the above error.

    The workaround is to use the string “UserInfo” instead of “User Information List”. I found it in the documentation here:

    http://msdn.microsoft.com/en-us/library/lists.lists.getlist.aspx

  14. Thanks for this Blake. Great tip. Cheers.

  15. HI Darren, Very nice job!
    I am new on wss, and I wonder if I can get the current user picture and show it in a image webpart?

    Thanks in advance

  16. Hey there,

    I’m trying to get this thing to work, but I always get an error: Internal Server Error.
    Can you help me with this?

    Thanks in advance!

    Greez,
    Mark

Post a Response