SharePoint REST API: Get User Id by User Name
Introduction
This is not an article, but a small tip. In certain cases, it is required to fetch
UserId
of particular site users inSharePoint. This tip may be helpful in getting UserId
for site user by passing login name. SharePoint provides OOB REST APIs to get site users, however, with login name format, which is dependent upon SharePointenvironment, it becomes little tricky.
The REST endpoint to get site users is : http://<site url>/_api/web/siteusers(@v)?@v='<pass login name>'
Using the Code
The below code can be included on your page to fetch the
UserId
of a given Site User.
Hide Shrink
Copy Code
//
// Include JQuery reference
// ... script continues ...
/// username should be passed as 'domain\username'
function GetUserId(userName) {
/// change this prefix according to the environment.
/// In below sample, windows authentication is considered.
var prefix = "i:0#.w|";
/// get the site url
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
/// add prefix, this needs to be changed based on scenario
var accountName = prefix + userName;
/// make an ajax call to get the site user
$.ajax({
url: siteUrl + "/_api/web/siteusers(@v)?@v='" +
encodeURIComponent(accountName) + "'",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
///popup user id received from site users.
alert("Received UserId" + data.d.Id);
alert(JSON.stringify(data));
},
error: function (data) {
console.log(JSON.stringify(data));
}
});
}
- For SharePoint Online or on-premise forms authentication, use the below login name format:Hide Copy Code
i: 0#.f|membership|user@domain.com
- For SharePoint 2013 on-premise Windows authentication, use the below login name format:Hide Copy Code
i: 0#.w|domain\user
- For SharePoint 2013 on-premise SAML based authentication, use the below login name format:Hide Copy Code
?i: 05:t|adfs with roles|user@domain.com
For examples of login names and further information, refer to 'table 1 Login name formats' in MSDN link:http://msdn.microsoft.com/en-us/library/office/dn531432(v=office.15).aspx.
Points of Interest
Without appending the login name format prefix, SharePoint returns error HTTP 500, hence it is important to identify suitable login format according to the environment and set as prefix on login name.
References: User, Groups and Roles, REST API reference and example:
No comments:
Post a Comment