Follow my blog for more interesting topics on Dynamics 365, Portals and Power Platform. For training and consulting, write to us at email@example.com
If you are directly on this blog post, I suggest you start from the first blog post of this series to get the context.
So I am on the final blog of this series. And here I am going to generate the authentication token to finally connect to SharePoint. Here we will deal with two most important properties of the Add-in, Add-In ID and Add-In Secret. Using these two properties now we will construct the access token.
Let us achieve this in the following steps
- Open your VS and create a Console Application. ( I am using VS 2017 and created a console application with .Net framework 4.6.2)
- After your project is created we need to add the SharePoint Dependencies. To do this right click on References and Manage NuGet packages and look for a package named AppForSharePointOnlineWebToolkit and install the package.
While trying to add the reference you may face an issue saying Microsoft.IdentityModel.dll was not found so package could not be installed.
If that’s the case, add Microsoft.IdentityModel.dll using NuGet package.
- Post doing step 3 as well you will not be able to reference SharePoint Dependencies since it again looks for another dll named Microsoft.IdentityModel.Extensions dll.
- Include the reference for Microsoft.IdentityModel.Extensions.dll
- Now let us try to install the package named AppForSharePointOnlineWebToolkit. Not only this package will add the SharePoint Dependencies but also includes the class files TokenHelper.cs and SharePointContext.cs
- Now we have included all the dependencies required for the operation. Make sure to include the below configuration in App.config file
- Use the Client ID and Client Secret of the Add-In and replace its values in App.Config file. This is because TokenHelper.cs class will grab the id and secret from the application’s configuration file. Add the following piece of code in your application to generate the token.
string siteUrl = "https://xrm20208.sharepoint.com";
//Get the realm for the URL
string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(siteUrl));
//Get the access token for the URL.
string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, new Uri(siteUrl).Authority, realm).AccessToken;
- As you can see in the below screenshot my token is generated successfully.
Yahoo! Now that is some relief right? The token is now generated and you can passing it as a bearer token while making any calls to SharePoint REST API. I am not going to show you how you are now going to consume the REST API. We have innumerable good SharePoint blogs for the same. So I leave the remaining part for you to explore.
Hope this helps!