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
- SharePoint Framework web part docs
- SharePoint Framework extension docs
- Getting Started SharePoint Framework Solution Videos
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");
}
});
Is the LoginName you inspect different than the LoginName that is already in the page’s source in the “spClientSidePageContext” object?
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
Good Work.
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