web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Getting Security Role Name for logged-in user in Dynamics using Xrm.Page.context

(0) ShareShare
ReportReport
Posted on by 130

In one of the requirement, I need to show and hide some sections, tabs, fields on the basis of Security Roles of the logged-in user.

This method Xrm.Page.context.getUserRoles() returns an array of GUID of security roles. 

Then I will have to make OData query to get the name of security roles, Is there any other way to achieve this?

 

*This post is locked for comments

I have the same question (0)
  • Verified answer
    Guido Preite Profile Picture
    54,086 Moderator on at

    you should compare the security roles by the GUID, not by their names

  • AtulSharma Profile Picture
    130 on at

    For example, my security role name is - "Role1" and it's GUID is - "XXXYYZZZ"

    I checked for security roles GUID something like this 

    if (securityRole = "XXXYYZZZ")

    {

    //Then show some fields

    }

    else

    {

    //Hide the fields

    }

    If I move this from one environment to another, My security role will be Role1 but GUID will be changed. 

    In this scenario, I will have to update/change the GUID in that environment.

    Please confirm or correct my understanding.

  • Verified answer
    SCV Profile Picture
    1,004 on at

    Hi Athul,

    Try below code. Here you can pass the security roles you want in an array and it checks whether current user has got those roles. In the example I am checking whether the user has Sales Manager and System Administrator roles. If so it returns true; otherwise returns false. Hope it helps!

    var roles = [];
    roles[0] = "Sales Manager";
    roles[1] = "System Administrator";
    var hasUserGotSalesManagerAndAdminRole = currentUserHasSecurityRole(roles);
    
    function currentUserHasSecurityRole(roles) {
        var fetchXml =
            "<fetch mapping='logical'>" +
                "<entity name='systemuser'>" +
                "<attribute name='systemuserid' />" +
                "<filter type='and'>" +
                "<condition attribute='systemuserid' operator='eq-userid' />" +
                "</filter>" +
                "<link-entity name='systemuserroles' from='systemuserid' to='systemuserid' visible='false' intersect='true'>" +
                "<link-entity name='role' from='roleid' to='roleid' alias='r'>" +
                "<filter type='or'>";
    
        for (var i = 0; i < roles.length; i++) {
            fetchXml += "<condition attribute='name' operator='eq' value='" + roles[i] + "' />";
        }
    
        fetchXml += "            </filter>" +
            "</link-entity>" +
            "</link-entity>" +
            "</entity>" +
            "</fetch>";
        var modifiedFetchXml = fetchXml.replace("&", "&amp;");
        var users = ExecuteFetch(modifiedFetchXml, "systemusers");
        if (users > 0)
            return true;
        else
            return false;
    }
    
    function ExecuteFetch (originalFetch, entityname) {
        var count = 0;
        var fetch = encodeURI(originalFetch);
    
        var serverURL = Xrm.Page.context.getClientUrl();
        var Query = entityname + "?fetchXml=" + fetch;
        var req = new XMLHttpRequest();
        req.open("GET", serverURL + "/api/data/v8.0/" + Query, false);
        req.setRequestHeader("Accept", "application/json");
        req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        req.setRequestHeader("OData-MaxVersion", "4.0");
        req.setRequestHeader("OData-Version", "4.0");
        req.onreadystatechange = function () {
            if (this.readyState == 4 /* complete */) {
                req.onreadystatechange = null;
                if (this.status == 200) {
                    var data = JSON.parse(this.response);
                    if (data != null) {
                        count = data.value.length;
                    }
                }
                else {
                    var error = JSON.parse(this.response).error;
                    alert(error.message);
                }
            }
        };
        req.send();
        return count;
    };
    



  • Community Member Profile Picture
    on at

    See below link it may help you

    crmshop.wordpress.com/.../how-to-use-fetchxml-in-crm-web-api

  • Saddamk206 Profile Picture
    777 on at

    Hi

    you can try below code:-

     

    function CheckUserRole() {
    var _roleQuery = '';
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    for (var i = 0; i < currentUserRoles.length; i++) {

    if (i == 0)
    _roleQuery += 'roleid eq ' + currentUserRoles[i];
    else
    _roleQuery += ' or roleid eq ' + currentUserRoles[i];

    }

    var req = new XMLHttpRequest();
    req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.1/roles?$select=name" + '&$filter=' + _roleQuery, true);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function () {
    if (this.readyState === 4) {
    req.onreadystatechange = null;
    if (this.status === 200) {
    var results = JSON.parse(this.response);
    for (var i = 0; i < results.value.length; i++) {
    var roleName = results.value[i]["name"];
    if (roleName == "System Administrator") {

    ///perform a task

    }
    }
    } else {
    alert(this.statusText);

    }
    }
    };
    req.send();
    }


    CheckUserRole();

  • Suggested answer
    Ben Fishin Profile Picture
    on at

    No need to call server to get user role guids or names

    Get User Security Role Name from context in Dynamics 365 CE - Microsoft Dynamics CRM Community

    There was a bug but it has been fixed.

    Happy coding 

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans