示例#1
0
        /// <summary>
        /// Generates a valid authorization URI for use when doing OAuth authentication.
        /// </summary>
        /// <param name="plugin">The OAuth authentication plugin details.</param>
        /// <param name="state">The state - must not be empty/null - used to passed to the authorization endpoint.</param>
        /// <param name="forceLogin">If true then the user will be forced to log in, even if they have already authenticated recently.</param>
        /// <returns>The URI that can be shown in a browser to undertake the OAuth flow.</returns>
        public static Uri GenerateAuthorizationUri
        (
            this PluginInfo plugin,
            string state,
            bool forceLogin = false
        )
        {
            // Sanity.
            if (null == plugin)
            {
                throw new ArgumentNullException(nameof(plugin));
            }
            if (string.IsNullOrWhiteSpace(state))
            {
                throw new ArgumentNullException(nameof(state));
            }
            if (false == plugin.IsOAuthPlugin())
            {
                throw new ArgumentException("The authentication plugin does not refer to an OAuth authentication type", nameof(plugin));
            }
            var promptType  = forceLogin ? "login" : null;
            var redirectUri = plugin.GetAppropriateRedirectUri();

            // Build up the URI with mandatory data.
            var uriBuilder = new UriBuilder(plugin.Configuration["AuthorizationEndpoint"]?.ToString());

            uriBuilder.SetQueryParam("client_id", plugin.Configuration["ClientID"]?.ToString());
            uriBuilder.SetQueryParam("redirect_uri", redirectUri);
            uriBuilder.SetQueryParam("response_type", "code");

            // Add the optional items, if set.
            uriBuilder.SetQueryParamIfNotNullOrWhitespace("scope", plugin.Configuration["Scope"]?.ToString());
            uriBuilder.SetQueryParamIfNotNullOrWhitespace("state", state);
            uriBuilder.SetQueryParamIfNotNullOrWhitespace("prompt", promptType);
            uriBuilder.SetQueryParamIfNotNullOrWhitespace("resource", plugin.Configuration["Resource"]?.ToString());

            // Return the generated URI.
            return(uriBuilder.Uri);
        }