Created
March 18, 2014 14:48
-
-
Save ahelland/9621575 to your computer and use it in GitHub Desktop.
Office 365 SharePoint/OneDrive REST API snippet.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public ActionResult Stats() | |
{ | |
var authorizationEndpoint = "https://login.windows.net/"; | |
var resource = "https://graph.windows.net"; | |
//Change port number to whatever your Visual Studio has chosen for you | |
var redirectURI = "https://localhost:44300/Home/CatchCode"; | |
string authorizationUrl = string.Format("{0}{1}/oauth2/authorize?&response_type=code&client_id={2}&resource={3}&redirect_uri={4}", | |
authorizationEndpoint, | |
ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value, | |
AppPrincipalId, | |
resource, | |
redirectURI); | |
return Redirect(authorizationUrl); | |
} | |
public async Task<ActionResult> CatchCode(string code) | |
{ | |
var tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value; | |
var appRedirect = "https://localhost:44300/Home/CatchCode"; | |
//Replace these variables with details from your tenant | |
var sharepointUrl = "https://contoso-my.sharepoint.com/"; | |
var sharepointUsername = "andreas_contoso_onmicrosoft_com"; | |
AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, LoginUrl, tenantId)); | |
ClientCredential credential = new ClientCredential(AppPrincipalId, AppKey); | |
var assertionCredential = authContext.AcquireTokenByAuthorizationCode(code, new Uri(appRedirect), credential); | |
string authHeader = string.Empty; | |
if (assertionCredential.IsMultipleResourceRefreshToken) | |
{ | |
AuthenticationResult arSP = authContext.AcquireTokenByRefreshToken(assertionCredential.RefreshToken, AppPrincipalId, credential, sharepointUrl); | |
authHeader = arSP.CreateAuthorizationHeader(); | |
} | |
var skyGetAllFilesCommand = sharepointUrl + | |
"/personal/" + | |
sharepointUsername + | |
"/_api/web/GetFolderByServerRelativeUrl('/personal/"+ | |
sharepointUsername + | |
"/Documents/Shared%20with%20Everyone')/Files"; | |
HttpClient client = new HttpClient(); | |
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, skyGetAllFilesCommand); | |
request.Headers.TryAddWithoutValidation("Authorization", authHeader); | |
HttpResponseMessage response = await client.SendAsync(request); | |
string responseString = await response.Content.ReadAsStringAsync(); | |
ViewBag.skyResponse = responseString; | |
return View(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment