从SharePoint中的my javascript确定当前用户

从SharePoint中的my javascript确定当前用户,javascript,sharepoint,azure-active-directory,sharepoint-online,Javascript,Sharepoint,Azure Active Directory,Sharepoint Online,登录SharePoint时,.office.com上会设置一个名为“AADAuth”的cookie。这个cookie的内容是一个JWT,它肯定地标识了当前用户。如果我可以从SharePoint中的javascript中获取此cookie,我可以将JWT发送到我的自定义API,并使用Microsofts公共证书,我将能够肯定地验证用户的身份 但是,由于此cookie位于“.office.com”上,而“.office.com”显然不是我的SharePoint域,因此我无法访问该cookie 那么,

登录SharePoint时,.office.com上会设置一个名为“AADAuth”的cookie。这个cookie的内容是一个JWT,它肯定地标识了当前用户。如果我可以从SharePoint中的javascript中获取此cookie,我可以将JWT发送到我的自定义API,并使用Microsofts公共证书,我将能够肯定地验证用户的身份

但是,由于此cookie位于“.office.com”上,而“.office.com”显然不是我的SharePoint域,因此我无法访问该cookie

那么,有没有办法在SharePoint上获得JWT

否则,是否有任何其他方法可以在客户端javascript上找到任何内容来明确标识当前用户


我知道我可以从SharePoint中的javascript启动新的身份验证过程,但这需要时间,我正在寻找一种对最终用户来说不需要太多时间的解决方案,因此,希望我可以使用SharePoint中已有的一些信息。

您可以获取
\u spPageContextInfo.userId
\u spPageContextInfo.userLoginName


有关该对象的更多信息

您可以获取
\u spPageContextInfo.userId
\u spPageContextInfo.userLoginName


关于该对象的更多信息

我将介绍几种不同的方法,因为您可能正在寻找一种专门的解决方案,而不是通用的解决方案

通用解决方案

我将使用
\u spPageContextInfo.userId
扩展DevBot的答案,它是一个数字,而不是用户的用户名

<script type="text/javascript">
    var spContextUserId;
    $(document).ready(function() {
        spContextUserId = _spPageContextInfo.userId;
        console.log('user context id: ' + spContextUserId);     

        console.log('Executing sp.js...');
        SP.SOD.executeOrDelayUntilScriptLoaded(loadSPUserProfiles, 'sp.js');    

    });

    function loadSPUserProfiles() {
        // ..wait for sp.js to load
        console.log('sp.js loaded.  Loading sp.userprofiles.js...');
        SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');        
    }

</script>
<script type="text/ecmascript">
    var userProfileProperties;

    function getUserProperties() {
        try {
            console.log('sp.userprofiles.js loaded...');    
            console.log('Getting user properties...');
            var clientContext = new SP.ClientContext.get_current();
            var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
            userProfileProperties = peopleManager.getMyProperties();
            clientContext.load(userProfileProperties);
            clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
        }
        catch (err) {
            console.log(err.message);
        }
    }

    function onRequestSuccess() {
        console.log('in request success routine');
        var accountName = "";

        try {
            //console.log(userProfileProperties);
            //accountName = userProfileProperties.get_accountName; // also works
            accountName = userProfileProperties.get_userProfileProperties()['AccountName'];
            console.log('accountName from svc: ' + accountName);

            // Now see if that account name matches the ID
            getUserInfo(accountName, function(userInfo){
               console.log('User Id: ' + userInfo.ID);
               if (spContextUserId == userInfo.ID) {
                   alert('Verified');
               } else {
                   alert('Not verified.');
               }
           },
           function(sender,args){
              console.log(args.get_message());
           });                

        catch(ex) {
           console.log(ex.message);
      }

     function getUserInfo(userName, Success, Error)
     {
         var context = new SP.ClientContext.get_current();
         var userInfoList = context.get_web().get_siteUserInfoList();
         var query = new SP.CamlQuery();
         var viewXml = "<View> \
                <Query> \
                   <Where> \
                       <Eq><FieldRef Name='UserName' /><Value Type='Text'>" + userName + "</Value></Eq> \
                   </Where>  \
                </Query> \
                <RowLimit>1</RowLimit> \
              </View>";
         query.set_viewXml(viewXml);
         var items = userInfoList.getItems(query);
         context.load(items,'Include(Deleted,Department,EMail,FirstName,ID,IsActive,IsSiteAdmin,JobTitle,LastName,MobilePhone,Name,Notes,Office,Picture,SipAddress,UserName,WebSite,WorkPhone)');
         context.executeQueryAsync(function() {
             if(items.get_count() > 0) {
                 var item = items.itemAt(0);
                 Success(item.get_fieldValues());
             }
             else {
                 Success(null);
             }   
         }, Error);
    }
</script>
您已经在
web.config
中设置了
重定向URI

<configuration>
    <appSettings>
        <add key="RedirectUri" value="https://contoso.com/RedirectAccept.aspx" />
    </appSettings>
<configuration>
  • IsDlg=1
    将启动身份验证对话框
  • 客户端id
    必须与您的加载项在SharePoint中注册时相同
也许这可以作为AJAX调用中的
GET
。Microsoft谈到将用户重定向到此URL,这向我表明这将是一个实际更改URL的调用:

window.location.href = 'http://www.mysharepointsite.com/somesite/oauthorize.aspx?...';
我的建议是彻底审查此文档,并使用以下信息构建他们所说的您需要/执行所需的重定向:


如果没有更多关于您如何访问SharePoint的信息,以及为什么您认为令牌方法是验证帐户的唯一方法,那么这是一个很难回答的问题,因为您可能有一个特定的场景,您正试图构建该场景,并且通常会涉及大量的尝试和错误,以确保所有权限、GUID、,等等都是注册的、准确的。

我将介绍几种不同的方法,因为您可能正在寻找一种专门的解决方案,而不是一般的解决方案

通用解决方案

我将使用
\u spPageContextInfo.userId
扩展DevBot的答案,它是一个数字,而不是用户的用户名

<script type="text/javascript">
    var spContextUserId;
    $(document).ready(function() {
        spContextUserId = _spPageContextInfo.userId;
        console.log('user context id: ' + spContextUserId);     

        console.log('Executing sp.js...');
        SP.SOD.executeOrDelayUntilScriptLoaded(loadSPUserProfiles, 'sp.js');    

    });

    function loadSPUserProfiles() {
        // ..wait for sp.js to load
        console.log('sp.js loaded.  Loading sp.userprofiles.js...');
        SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');        
    }

</script>
<script type="text/ecmascript">
    var userProfileProperties;

    function getUserProperties() {
        try {
            console.log('sp.userprofiles.js loaded...');    
            console.log('Getting user properties...');
            var clientContext = new SP.ClientContext.get_current();
            var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
            userProfileProperties = peopleManager.getMyProperties();
            clientContext.load(userProfileProperties);
            clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
        }
        catch (err) {
            console.log(err.message);
        }
    }

    function onRequestSuccess() {
        console.log('in request success routine');
        var accountName = "";

        try {
            //console.log(userProfileProperties);
            //accountName = userProfileProperties.get_accountName; // also works
            accountName = userProfileProperties.get_userProfileProperties()['AccountName'];
            console.log('accountName from svc: ' + accountName);

            // Now see if that account name matches the ID
            getUserInfo(accountName, function(userInfo){
               console.log('User Id: ' + userInfo.ID);
               if (spContextUserId == userInfo.ID) {
                   alert('Verified');
               } else {
                   alert('Not verified.');
               }
           },
           function(sender,args){
              console.log(args.get_message());
           });                

        catch(ex) {
           console.log(ex.message);
      }

     function getUserInfo(userName, Success, Error)
     {
         var context = new SP.ClientContext.get_current();
         var userInfoList = context.get_web().get_siteUserInfoList();
         var query = new SP.CamlQuery();
         var viewXml = "<View> \
                <Query> \
                   <Where> \
                       <Eq><FieldRef Name='UserName' /><Value Type='Text'>" + userName + "</Value></Eq> \
                   </Where>  \
                </Query> \
                <RowLimit>1</RowLimit> \
              </View>";
         query.set_viewXml(viewXml);
         var items = userInfoList.getItems(query);
         context.load(items,'Include(Deleted,Department,EMail,FirstName,ID,IsActive,IsSiteAdmin,JobTitle,LastName,MobilePhone,Name,Notes,Office,Picture,SipAddress,UserName,WebSite,WorkPhone)');
         context.executeQueryAsync(function() {
             if(items.get_count() > 0) {
                 var item = items.itemAt(0);
                 Success(item.get_fieldValues());
             }
             else {
                 Success(null);
             }   
         }, Error);
    }
</script>
您已经在
web.config
中设置了
重定向URI

<configuration>
    <appSettings>
        <add key="RedirectUri" value="https://contoso.com/RedirectAccept.aspx" />
    </appSettings>
<configuration>
  • IsDlg=1
    将启动身份验证对话框
  • 客户端id
    必须与您的加载项在SharePoint中注册时相同
也许这可以作为AJAX调用中的
GET
。Microsoft谈到将用户重定向到此URL,这向我表明这将是一个实际更改URL的调用:

window.location.href = 'http://www.mysharepointsite.com/somesite/oauthorize.aspx?...';
我的建议是彻底审查此文档,并使用以下信息构建他们所说的您需要/执行所需的重定向:


如果没有更多关于您如何访问SharePoint的信息,以及为什么您认为令牌方法是验证帐户的唯一方法,那么这是一个很难回答的问题,因为您可能有一个特定的场景,您正试图构建该场景,并且通常会涉及大量的尝试和错误,以确保所有权限、GUID、,等都已注册且准确。

用例是,我想将此用户id发送到我的自定义API,然后该API将相信调用的用户确实是具有此id的用户。我认为,仅使用一个简单的用户id是不够的,这就是JWT如此出色的原因。因此,我正在寻找一种方法来获取JWT或任何能给我提供我真正信任的信息的替代品。@NielsBrinch如果你访问一个网址时可以访问“JWT”,你可以使用shdocvw.internetexplorer-通过页面刮取来获取它的内容。但是上面提到的这些ID可以通过API本身根据SharePoint进行验证。给定一个
\u spPageContextInfo.userId
,这是一个数字,您可以让API获取它并执行CAML查询以获取用户名,然后验证此名称是否与他们登录时使用的名称相同。用例是,我希望将此用户id发送到我的自定义API,然后自定义API将信任调用的用户确实是具有此id的用户。我认为,仅使用一个简单的用户id是不够的,这就是JWT如此出色的原因。因此,我正在寻找一种方法来获取JWT或任何能给我提供我真正信任的信息的替代品。@NielsBrinch如果你访问一个网址时可以访问“JWT”,你可以使用shdocvw.internetexplorer-通过页面刮取来获取它的内容。但是上面提到的这些ID可以通过API本身根据SharePoint进行验证。给定一个
\u spPageContextInfo.userId
,这是一个数字,您可以让API获取它并执行CAML查询以获取用户名,然后验证此名称是否与他们登录时使用的名称相同。