Wednesday, May 17, 2017

How to get context token of O365 in On-Prem web applications

Spent lot of time to get O365 context token in our on-prem SharePoint site to access SharePoint online content using single sign-on.

I would like to bring the situation in front before explaining the implementations. One of our customer has SharePoint On-Prem environment and O365 including SharePoint online and one drive for business. They recently configured O365 Cloud Hybrid Search, and plan to replace SharePoint Enterprise search using O365 Cloud Hybrid Search. We have got all information.

But when user search for any content from SharePoint on-prem site, it redirect to O365 login page then get the domain user name, then using ADFS for authentication  finally landing at the search result page of O365.

All three redirection is taking almost 10-20 seconds to reach search result page. This will happen when user accessing SharePoint Online site/office components very first time. Once it is accessed then the browser hold the context token then using the same for next O365 content access in the day.

We have tried many approaches to get O365 context token but finally failed because if we use custom C# code then need to pass the credential (user name and password) which is not aligned for single sign on, not able to use domain libraries also below approaches and ends with CORS issue.

1. Loading an profile image from O365 to on-prem page - failed
2. used CSS to call O365 image - failed
3. Used javascript variables to access O365 pages - failed.
4. Used iframe to access O365 portal -failed.

Spent enough amount of time finally got a breakthrough using iframe only but accessing different page.

Microsoft said that SharePoint sites page from O365 is accessible in iframe. We have tried accessing SharePoint page from html and SharePoint pages and found that it has created a context token. 

< iframe src="https://login.microsoftonline.com/login.srf?wa=wsignin1.0&whr=kmstechs.com&wreply=https%3A%2F%2Fkmstechs.sharepoint.com%2F_layouts%2F15%2Fsharepoint.aspx" style="visibility:hidden" > </iframe >

1. Added a hidden content editor web part and place below iframe tag to create context token in the page.
2. The context token will be created whenever the site is loaded thereafter if user searches for any content then the request used already generated context token redirecting directly to O365 search result page.

Happy working with SharePoint :-)