示例#1
0
        public string CompleteOAuthFlow(AuthorizationParameters parameters)
        {
            // Look up the email from the guid/user map.
            string userEmail = Storage.AppConfigCache.GetUserFromStateGuid(parameters.State);

            if (string.IsNullOrEmpty(userEmail))
            {
                // Per the Azure docs, the response from the auth code request has
                // to include the value of the state parameter passed in the request.
                // If it is not the same, then you should not accept the response.
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.OK,
                                                                            "Unknown state returned in OAuth flow."));
            }

            try
            {
                // Get authorized for the discovery service
                ClientCredential      credential  = new ClientCredential(ClientId, ClientSecret);
                string                authority   = string.Format(CultureInfo.InvariantCulture, OAuthUrl, "common");
                AuthenticationContext authContext = new AuthenticationContext(authority);
                AuthenticationResult  result      = authContext.AcquireTokenByAuthorizationCode(
                    parameters.Code, new Uri(RedirectUrl.GetLeftPart(UriPartial.Path)), credential, DiscoveryResource);

                // Cache the refresh token
                Storage.AppConfig appConfig = new Storage.AppConfig();
                appConfig.RefreshToken = result.RefreshToken;

                // Use the access token to get the user's OneDrive URL
                OneDriveServiceInfo serviceInfo = DiscoverServiceInfo(result.AccessToken);
                appConfig.OneDriveResourceId  = serviceInfo.ResourceId;
                appConfig.OneDriveApiEndpoint = serviceInfo.Endpoint;

                // Save the user's configuration in our confic cache
                Storage.AppConfigCache.AddUserConfig(userEmail, appConfig);
                return("OAuth succeeded. Please close this window to continue.");
            }
            catch (ActiveDirectoryAuthenticationException ex)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.OK,
                                                                            "OAuth failed. " + ex.ToString()));
            }
        }
示例#2
0
            internal async static Task <Office365ServiceInfo> CreateAsync()
            {
                // Attempt to build an Office365ServiceInfo object based on cached API endpoint & resource ID information:
                Office365ServiceInfo info = new OneDriveServiceInfo()
                {
                    ResourceId  = (string)Office365Helper.GetFromCache("OneDriveResourceId"),
                    ApiEndpoint = (string)Office365Helper.GetFromCache("OneDriveApiEndpoint")
                };

                // If the cached Resource ID and API Endpoint are not empty, then use them:
                if ((info.ResourceId != null) && (info.ApiEndpoint != null))
                {
                    info.AccessToken = await Office365Helper.GetAccessToken(info.ResourceId);

                    return(info);
                }

                // If did not return above, invoke the Discovery Service to obtain the resource ID and API endpoint:
                DiscoveryServiceInfo discoveryServiceInfo = await DiscoveryServiceInfo.CreateAsync();

                if (!discoveryServiceInfo.HasValidAccessToken)
                {
                    // Cannot communicated with Service Discovery, so return the empty SharePointOneDriveServiceInfo as is.
                    //     The missing access token will let the caller know that the service is not ready to be used.
                    return(info);
                }

                DiscoveryResult[] results = await discoveryServiceInfo.DiscoverServicesAsync();

                DiscoveryResult myFilesEndpoint = results.First(result => result.Capability == "MyFiles");

                // Update and cache the resource ID and API endpoint:
                info.ResourceId  = myFilesEndpoint.ServiceResourceId;
                info.ApiEndpoint = myFilesEndpoint.ServiceEndpointUri;
                Office365Helper.SaveInCache("OneDriveResourceId", info.ResourceId);
                Office365Helper.SaveInCache("OneDriveApiEndpoint", info.ApiEndpoint);
                info.AccessToken = await Office365Helper.GetAccessToken(info.ResourceId);

                return(info);
            }
示例#3
0
        public static OneDriveServiceInfo DiscoverServiceInfo(string accessToken)
        {
            OneDriveServiceInfo serviceInfo = null;

            // Create a GET request to the discovery endpoint
            HttpWebRequest discoveryRequest =
                WebRequest.CreateHttp(DiscoveryUrl);

            discoveryRequest.Headers.Add("Authorization", string.Format("Bearer {0}", accessToken));
            discoveryRequest.Method = "GET";
            discoveryRequest.Accept = "application/json";

            HttpWebResponse discoveryResponse = (HttpWebResponse)discoveryRequest.GetResponse();

            if (discoveryResponse.StatusCode == HttpStatusCode.OK)
            {
                Stream       discoveryResponseStream = discoveryResponse.GetResponseStream();
                StreamReader discoveryReader         = new StreamReader(discoveryResponseStream);
                string       discoveryPayload        = discoveryReader.ReadToEnd();

                // Deserialize the JSON response
                var discoveryResult = JsonConvert.DeserializeObject <dynamic>(discoveryPayload);

                foreach (var service in discoveryResult.value)
                {
                    // Look for the entry that matches OneDrive
                    if (String.Compare(service.capability.ToString(), OneDriveCapability) == 0)
                    {
                        serviceInfo = new OneDriveServiceInfo()
                        {
                            ResourceId = service.serviceResourceId.ToString(),
                            Endpoint   = service.serviceEndpointUri.ToString()
                        };
                        break;
                    }
                }
            }

            return(serviceInfo);
        }
示例#4
0
 /// <summary>
 /// Returns information about the SharePoint OneDrive for Business service, including its cached access token.
 /// The Resource ID and API Endpoint will be discovered automatically using a Discovery Service.
 /// On error, this method will display an error message to the user, and return an
 ///     Office365ServiceInfo instance whose HasValidAccessToken property is set to "false".
 /// </summary>
 public static async Task <Office365ServiceInfo> GetOneDriveServiceInfoAsync()
 {
     return(await OneDriveServiceInfo.CreateAsync());
 }