Getting the Current User Name or ID in SharePoint using SharePoint Designer (no code)


A colleague sparked my interest in this today by asking me if getting the current user ID was possible without writing code.  This would be a very trivial task by creating a custom web part but with that comes deployment, maintenance, support, etc.  He had a simple requirement to pass the UserID in the query string and thought it would be overkill to do this using code, and I agreed.  This put me on a mission to find out if this was possible using SharePoint designer.  The usual Internet searches didn’t return anything useful so once I figured it out I decided that this needed to be posted somewhere.  So here is how you do it:


 


Using SharePoint designer open up the Data Source Library Pane


Hover over any library or list, using the drop down select “Show Data”


image


Next you will want to have SharePoint Designer insert a DataFormWebPart for you.  These last two steps aren’t really necessary, you could write all the markup by hand, but I find it is usually easier to have SPD do this for you, and then go back and clean it up, than it is to remember everything that you need and start from scratch.  For this part I selected the Title field and used a Multiple Item View Form, you can select different fields/views as your situation calls for.


image


Now we can get to what this post was really about, getting the UserName and/or the User ID.  To get the UserName all you need to do is add an XSL parameter.  A little known fact here is that any parameter that is found in the parameter bindings section of the data source element can also be passed to the XSL using an XSL parameter.  To be clear about what I added refer to the screen shot below, I have removed all the irrelevant XSL to make this easier to understand.


image 


The above will show you the what SharePoint display’s the user name as.  This was a step in the right direction, but I still needed to actual user ID.  To get this I decided to go the server variable route.  Here is the documentation straight from MSDN on the three variables that are probably of interested for this situation.













AUTH_USER


The name of the user as it is derived from the authorization header sent by the client, before the user name is mapped to a Windows account. This variable is no different from REMOTE_USER. If you have an authentication filter installed on your Web server that maps incoming users to accounts, use LOGON_USER to view the mapped user name.


LOGON_USER


The Windows account that the user is impersonating while connected to your Web server. Use REMOTE_USER, UNMAPPED_REMOTE_USER, or AUTH_USER to view the raw user name that is contained in the request header. The only time LOGON_USER holds a different value than these other variables is if you have an authentication filter installed.


REMOTE_USER


The name of the user as it is derived from the authorization header sent by the client, before the user name is mapped to a Windows account. If you have an authentication filter installed on your Web server that maps incoming users to accounts, use LOGON_USER to view the mapped user name.


I decided to use the LOGON_USER variable, but note that you can use any server variable here, your not limited by SPD in any way.  To do this I had to add the server variable to the ParameterBindings as well as the XSL.  The end result of my DataFormWebPart is below.

<WebPartPages:DataFormWebPart runat=”server”
IsIncluded=”True”
FrameType=”None”
NoDefaultStyle=”TRUE”
ViewFlag=”0″
Title=”Shared Documents”
ListName=”{EF49CFE7-C6C4-42D6-8FCB-B10D6CDC0A35}”
Default=”FALSE”
DisplayName=”Shared Documents”
__markuptype=”vsattributemarkup” _
_WebPartId=”{E39B973F-F567-4AE6-9913-36710D1ADA1A}”
id=”g_e39b973f_f567_4ae6_9913_36710d1ada1a”
__AllowXSLTEditing=”true”
WebPart=”true”
Height=””
Width=”” __WebPartId=”{633D5B43-5675-4363-8F69-9BA87A3776ED}”>
<DataSources>
<SharePoint:SPDataSource runat=”server”
DataSourceMode=”List”
UseInternalName=”true”
selectcommand=”&lt;View&gt;&lt;/View&gt;”
id=”Shared_x0020_Documents1″><SelectParameters><WebPartPages:DataFormParameter
Name=”ListID”
ParameterKey=”ListID”
PropertyName=”ParameterValues”
DefaultValue=”EF49CFE7-C6C4-42D6-8FCB-B10D6CDC0A35″/>
</SelectParameters></SharePoint:SPDataSource>
</DataSources>
<ParameterBindings>
<ParameterBinding Name=”ListID” Location=”None” DefaultValue=”EF49CFE7-C6C4-42D6-8FCB-B10D6CDC0A35″/>
<ParameterBinding Name=”dvt_apos” Location=”Postback;Connection”/>
<ParameterBinding Name=”UserID” Location=”CAMLVariable” DefaultValue=”CurrentUserName”/>
<ParameterBinding Name=”Today” Location=”CAMLVariable” DefaultValue=”CurrentDate”/>
<ParameterBinding Name=”LogonUser” Location=”ServerVariable(LOGON_USER)”/>
</ParameterBindings>
<datafields>@FileLeafRef,Name (for use in forms);@Title,Title;@Approval,Approval;
@CollectS,Collect Signatures;@CollectF,Collect Feedback;@ID,ID;@ContentType,Content Type;
@Created,Created;@Author,Created By;@Modified,Modified;@Editor,Modified By;
@_CopySource,Copy Source;@CheckoutUser,Checked Out To;@_CheckinComment,Check In Comment;
@CheckedOutTitle,Checked Out To;@CheckedOutUserId,ID of the User who has the item Checked Out;
@FileDirRef,Path;@FSObjType,Item Type;@HTML_x0020_File_x0020_Type,HTML File Type;
@File_x0020_Type,File Type;@IsCheckedoutToLocal,Is Checked out to local;@_SourceUrl,Source Url;
@_HasCopyDestinations,Has Copy Destinations;@ContentTypeId,Content Type ID;@_ModerationStatus,Approval Status;
@_UIVersion,UI Version;@Created_x0020_Date,Created;@FileRef,URL Path;@File_x0020_Size,File Size;
@_UIVersionString,Version;@ParentVersionString,Source Version (Converted Document);
@ParentLeafName,Source Name (Converted Document);@TemplateUrl,Template Link;</datafields>
<XSL>
<xsl:stylesheet xmlns:x=”http://www.w3.org/2001/XMLSchema”
xmlns:d=”http://schemas.microsoft.com/sharepoint/dsp”
version=”1.0″
exclude-result-prefixes=”xsl msxsl ddwrt”
xmlns:ddwrt=”http://schemas.microsoft.com/WebParts/v2/DataView/runtime”
xmlns:asp=”http://schemas.microsoft.com/ASPNET/20″
xmlns:__designer=”http://schemas.microsoft.com/WebParts/v2/DataView/designer”
xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”
xmlns:msxsl=”urn:schemas-microsoft-com:xslt”
xmlns:SharePoint=”Microsoft.SharePoint.WebControls”
xmlns:ddwrt2=”urn:frontpage:internal”>
<xsl:output method=”html” indent=”no”/>
<xsl:decimal-format NaN=””/>
<xsl:param name=”dvt_apos”></xsl:param>
<xsl:param name=”UserID”/>
<xsl:param name=”LogonUser”/>
<xsl:variable name=”dvt_1_automode”>0</xsl:variable>
<xsl:template match=”/”>

<xsl:value-of select=”$UserID”/><br/>
<xsl:value-of select=”$LogonUser”/>

</xsl:template>
</xsl:stylesheet> </XSL>
</WebPartPages:DataFormWebPart>



And the screen shot…
image  

 


And that does it, you can now show user name or user ID without using any code.  An important side lesson of this is the fact that you can use anything in the parameter binding session in your XSL as well. 


 


Hope this helps.



Comments (35)

  1. rom84 says:

    Thanks a lot! Great job!

    but I want to get all group permission of current user, Can use xslt do that?

  2. mike says:

    Thank you so much!  I’ve been racking my brain on this problem for a while.  Trying to do sharepoint development with the restriction of "No server-side code" allowed is tricky, and this technique is very valuable.

  3. Roennow says:

    Well – but you only solved part of  your colleagues problem which also included "…to pass the UserID in the query string …" !  

  4. Tuesday says:

    Is there a way to pull a list of the current user’s site group memberships?

    I want to show or hide a specific column based on whether or not the current user is a member of a custom Approvers group I set up.

    The only way I know to do it now is by User ID, which means anytime I have to change the list, I have to also alter the code that "hides" the column for non-approvers.

    Any ideas on how to do this without writing C#?

    Thanks,

    Tuesday

  5. Z says:

    if you enter [Me] as the default value for a text field and set it to calculated, it returns the userID

  6. Eric says:

    Thanks, works great!!  Anyone know how to pass this info on to an Oracle form or another app?

  7. Usman Ahmad says:

    Brilliant. Just brilliant.

    Thanks a bunch. Chill…

  8. Harikrishnan says:

    Can i do this with out using sharepoint designer?

    My case is like this i have a custom list which consist of a coulmn called NAME.When i click New i want to get the current users name on that Name field.

  9. Glynn says:

    Is there a way to store the current user name in a list?

  10. Emmanuel says:

    Hi,

    I would like to get the current user name in a variable that I can use in the XSL of my search result webpart. I would like to format my result list depending on a comparison between the current user and the "exracted to" field. Is there a way to do this ?

    Many thanks !

  11. chaitu.siva says:

    You are amazing ! Nice Approach

  12. EEG says:

    Can you have it show the logged in user in a specific field in a sharepoint form?

  13. Nasha says:

    I got the value of UserId returned using Javascript below.

    var abc = document.getElementById("WebPartg_641f8149_8c06_46c4_b2e6_91b55fd14776");

    alert("Hello " + abc.innerText );

    The value comes back inside a div tag. So need the id.

    Is there a better way?

  14. Kevin Wilbourn says:

    Nice method, allowed me to expose the UserID to javascript in order to prepopulate a people picker on a custom list form.  

    Used Andy Bonner’s method (http://cs.vbcity.com/blogs/skullcrusher/archive/2008/11/03/set-sharepoint-peoplepicker-field-mark-2.aspx) to populate the field, but needed an easy way to expose the UserID for Andy’s javascript to grab it.  This did the trick.

    Thanks again.

  15. Kalpana says:

    This is really great. I would also want to know if there a CAMLVariable to retrieve an user’s email ID?

  16. sara says:

    Nice !!!!!!!!

    get sharepoint user and group, it is simple.

    Try this too,

    <a href ="http://sarangasl.blogspot.com/2009/10/sharepoint-user-groups.html"><b>Get Current SharePoint user</b></a>

  17. sara says:

    Nice !!!!!!!!

    get sharepoint user and group, it is simple.

    Try this too,

    http://sarangasl.blogspot.com/2009/10/sharepoint-user-groups.html

  18. Tenorman says:

    Hi,

    Thank you for this. I used your code and it works great. I had an additional need.  I needed to filter my dataview based on a substring of LogonUser. In my case my LogonUser code are initials and numbers such as  P16012.  I had to filter based on just the numbers 6012. My  LogonUser presents  as COMSERVEP16012.

    So I added the following code to isolate just the numbers I need as a parameter

    <xsl:param name="LogonUser"/><xsl:param name="LoginNumbers"><xsl:value-of select="substring($LogonUser,12)"/></xsl:param>

    In the dataview I just filtered on the parameter added above

    [$LoginNumbers=@COM_x0020_ID]

    I hope others find this useful

  19. JK says:

    So close.  I am trying to take the a parameter like LoginNumbers above and set it as a parameter in a SqlDataSource UpdateQuery to update an operator field.  How to I reference back to that?

    Thank you.

  20. I can’t use the information from the pictures.  When I blow up the pictures, they are too blurry.

    I have also printed it out.  To hard to read pictures.

  21. Jeremy Green says:

    You can also do this for a SqlDataSource using a ControlParameter.  This lets you pass the user’s ID into a query before databinding.  I haven’t found a way to get the user’s name from this, though.

    <asp:SqlDataSource ID="Data" runat="server" ConnectionString="…" SelectCommand="SELECT @user UserID">

    <SelectParameters>

    <asp:ControlParameter Name="user" ControlID="Data" PropertyName="Page.Request.ServerVariables[‘AUTH_USER’]" />

    </SelectParameters>

    </asp:SqlDataSource>

    <asp:DetailsView runat="server" DataSourceID="Data" />

  22. spd1 says:

    Hi Tenorman,

    How did you get the domainuserID(P16012)?

    my LOGON_USER parameter gives me empty string.

  23. Chanda says:

    Thanks so much for this post.  I wanted to display the current user name in a custom list form and was able to simply include the following portion in the cell where I wanted it to show:

    <xsl:value-of select="$UserID"/>

    The only other task was to pass the parameter to the stylesheet (it was referenced in the parameter bindings section for the custom list form, just hadn’t been passed to be able to call from the xsl template):

    <xsl:param name="UserID"/>

    Thanks for the post! Chanda

  24. Santhosh says:

    Excellent Thank you so much…

  25. abs says:

    thank you for the article and special thank you to Jeremy Green for the sql connection details, I have been trying to do this for a while now and the sql connection thing is so simple and completely solves my problem! it's made it a great monday for me! 🙂

  26. aswin says:

    Thanks a lot… It really helped me alot. I was looking for the same kind of solution.

  27. propeller says:

    Good job. Another way to get the user id would be to simply hoover over the username and find the ID in the bottom left corner 🙂

  28. Aswin says:

    It's working like a charm…! Thanks you

  29. question says:

    This works great, I just wanna ask, how will I pass the value to a textbox?

  30. Bruno says:

    Hi, I can't make it work.

    We need to show the current username in a page of the sharepoint intranet, and have a link that's sends the username embed, like this:

    </a href='test.php?id=username'/>click here</a>

    Or any why that sends the username to an external site.

    Please help me, thanks

  31. Dhraga says:

    This helped me immensely, thank you!  I used it to filter a list of messages by the name…  been looking for this for a while.

    thanks again!

  32. Michael Christoffersen says:

    Your post has helped me a lot.

    However just for information, when we upgraded to SP2013, i finally realised that the username is prefixed with i:0#.w| because of som changes in the claims authorization mechanism. Take care in the SQL query.

  33. Shreyas ganta says:

    I am trying filter a external list by username. Unfortunately the list has loginname minus the 'domain ' .   Ideally I would like to perform  

    <ParameterBinding Name="LogonUser" Location="substring-after(ServerVariable(LOGON_USER),'')"/>

    to get the correct value to query.

    I am not sure how to achieve this. Please suggest a solution.

  34. Brian says:

    I just found this as well:

    <asp:LoginName runat="server" id="loginName" FormatString="<script>var _user = {0}</script>"></asp:LoginName>