Verify if the current user is internal or external in SPFx

In some of the SharePoint Framework solutions, it’s important to understand if the user is either or not an external user from your Office 365. With a few lines of code using the PnP.js, we can verify this.

In this example, I’ve used PnP.js library to get that information. The first step is to start a SharePoint Framework solution using the yeoman generator. Below, I’ll share the documentation as well as the recent playlist created to start with SharePoint Framework. There you can find instruction to create your first SharePoint Framework solution.

Documentation

To install the PnP.js, open the terminal of your SharePoint solution and then run the below command.

npm install @pnp/logging @pnp/common @pnp/odata @pnp/sp @pnp/graph --save 

Now with all the packages are installed. We can use the PnP.js library on our solution and the below code will allow you to understand if the current user is external or internal to your SharePoint. You can add this code directly to the OnInit().

// Include this at import files
import { sp } from "@pnp/sp"; 

// Add this code example on the onInit()
sp.setup({spfxContext: this.context});
 //CurrentUser properties
  sp.web.currentUser.get().then(result  => {
   if(result.LoginName.match("#ext#")){
     console.log("External User");
   }
   else{
    console.log("Internal User");
   }
});

4 Comments

  1. scott byrge said:

    Is the LoginName you inspect different than the LoginName that is already in the page’s source in the “spClientSidePageContext” object?

    September 23, 2019
    Reply
    • David Ramalho said:

      Hi Scott,

      They are the same objects but with this approach, it’s easier since you don’t have to do load|executeQuery.

      My best,
      David Ramalho

      September 23, 2019
      Reply
  2. Atul Goswami said:

    Good Work.

    July 2, 2020
    Reply
  3. Leif Frederiksen said:

    Hi – on the context.pageContext.user object there is a field called ‘isExternalGuestUser’.
    That field may also be useful in determining if the user is external.

    Regards
    Leif

    July 9, 2020
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *