This solution demonstrates how the PnP Core SDK can be extended to implement a persistent cache and reuse access tokens after application restart. After initial authentication the MSAL tokens are cached locally and when the application restarts there's no credential prompting needed anymore. This is realized by building a custom IAuthenticationProvider
.
Note
This sample was authored by Stefano Driussi 💪🥇 and the original source code can be found here. This code was copied to the PnP Core SDK samples after approval of the author, see this GitHub discussion for the background.
You can find the sample source code here: /samples/Demo.PersistentTokenCache
In order for the user to authenticate on the App, A new app registration should be created on Azure Portal
-
In App registrations, click New registration
-
Enter a name for your new app, make sure Accounts in this organizational directory only is selected. As the Redirect URI, change from Web Platform to "Mobile and Desktop Applications" use http://localhost for the redirect URI (only needed if you want use an interactive authentication flow)
-
Under Implicit grant section, check ID tokens and Access tokens
-
Under Advanced settings section, set Allow public client flows to yes
-
Go to API permissions section , click Add a permission
- Select Microsoft Graph > Delegated permissions > select Directory.Read.All
- Select Microsoft Graph > Delegated permissions > select User.Read
- Select Microsoft Graph > Delegated permissions > select ChannelMessage.Read.All
- Select Microsoft Graph > Delegated permissions > select ChannelMessage.Send
- Select Microsoft Graph > Delegated permissions > select TeamSettings.ReadWrite.All
- Select Microsoft Graph > Delegated permissions > select TeamsTab.ReadWrite.All
-
Click Grant admin consent for {tenant}
-
From Overview,
- copy the value of Directory (tenant) ID
- copy the value of Application (client) ID
- This demo application is configured directly inside
Program.cs
. Replace all parameters between curly braces with actual values from your SharePoint/Azure app. Be sure to have a Team in Microsoft Teams backing the modern team site in the above site collection
Hit F5 in Visual studio to execute the console app. The app will prompt for an interactive login (via a browser window). Execute the application a second time and the code will fetch the last access token without requiring any user interaction.