Question

I need to log into a SharePoint tenant using an admin account that uses MFA.

This is the code.

var authManager = new OfficeDevPnP.Core.AuthenticationManager();
var context = authManager.GetWebLoginClientContext(tenantUrl); 

// load some stuff

// this will fail with 403 Unauthorized
context.ExecuteQuery();

The login window does pop up for a second, but closes again immediately. I assume that it uses the cookie for my regular user (without SharePoint administration rights). The following requests that need tenant scope obviously do not work.

How can I clear the token cache so I can log in with the correct user? In the PnP PowerShell I had the same problem with -UseWebLogin, but there I can actually use the ClearTokenCache parameter and then it works. I have not yet found a similar option here, and PowerShell is not an option.

No correct solution

OTHER TIPS

Try using your code like below:

static void Main(string[] args) 
{ 
   string siteUrl = "https://<tenant-name>.sharepoint.com/sites/contosoteam"; 
   var authManager = new OfficeDevPnP.Core.AuthenticationManager(); 
   // This method calls a pop up window with the login page and it also prompts for the multi factor authentication code. 
   ClientContext ctx = authManager.GetWebLoginClientContext(siteUrl); 
   // The obtained ClientContext object can be used to connect to the SharePoint site. 
   Web web = ctx.Web; 
   ctx.Load(web, w => w.Title); 
   ctx.ExecuteQuery(); 
   Console.WriteLine("You have connected to {0} site, with Multi Factor Authentication enabled!!", web.Title); 
}

I understand you want to switch to another user but authManager just grab and use the existing cache, which causes it auto login with existing account.

In fact the login window use IE as the web browser control, So you can clear the cache in Internet Option:

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top