使用 HttpListener 对 Windows 桌面应用程序进行 OAuth 2.0 授权

Cri*_*n18 2 c# httplistener google-authentication oauth-2.0 asp.net-web-api

我正在用 C# 编写一个带有外部身份验证(Google、Facebook)的 Windows 桌面应用程序。

我正在使用 HttpListener 来允许用户通过带有 ASP.NET Web API 的外部身份验证服务获取 Barer 令牌,但为此需要管理员权限,我想在没有管理员模式的情况下运行。

我的参考资料是适用于 Windows 的示例桌面应用程序

这是来自 C# 的外部身份验证提供程序的最佳实践吗?或者有另一种方法可以做到这一点?

这是我通过外部提供商获取 Barer 令牌的代码:

public static async Task<string> RequestExternalAccessToken(string provider)
{
    // Creates a redirect URI using an available port on the loopback address.
    string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, GetRandomUnusedPort());

    // Creates an HttpListener to listen for requests on that redirect URI.
    var http = new HttpListener();
    http.Prefixes.Add(redirectURI);
    http.Start();

    // Creates the OAuth 2.0 authorization request.
    string authorizationRequest = Properties.Settings.Default.Server
        + "/api/Account/ExternalLogin?provider="
        + provider
        + "&response_type=token&client_id=desktop"
        + "&redirect_uri="
        + redirectURI + "?";

    // Opens request in the browser.
    System.Diagnostics.Process.Start(authorizationRequest);

    // Waits for the OAuth authorization response.
    var context = await http.GetContextAsync();

    // Sends an HTTP response to the browser.
    var response = context.Response;
    string responseString = string.Format("<html><head></head><body></body></html>");
    var buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
    response.ContentLength64 = buffer.Length;
    var responseOutput = response.OutputStream;
    Task responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) =>
    {
        responseOutput.Close();
        http.Stop();
        Console.WriteLine("HTTP server stopped.");
    });

    // Checks for errors.
    if (context.Request.QueryString.Get("access_token") == null)
    {
        throw new ApplicationException("Error connecting to server");
    }

    var externalToken = context.Request.QueryString.Get("access_token");

    var path = "/api/Account/GetAccessToken";

    var client = new RestClient(Properties.Settings.Default.Server + path);
    RestRequest request = new RestRequest() { Method = Method.GET };
    request.AddParameter("provider", provider);
    request.AddParameter("AccessToken", externalToken);
    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

    var clientResponse = client.Execute(request);

    if (clientResponse.StatusCode == HttpStatusCode.OK)
    {
        var responseObject = JsonConvert.DeserializeObject<dynamic>(clientResponse.Content);

        return responseObject.access_token;
    }
    else
    {
        throw new ApplicationException("Error connecting to server", clientResponse.ErrorException);
    }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*her 5

我不了解 Facebook,但通常(我对 Google OAuth2 和 Azure AD 以及 Azure AD B2C 有经验),身份验证提供程序允许您使用自定义URI 方案进行身份验证回调,例如badcompany://auth

为了获得身份验证令牌,我最终实施了以下方案(所有代码均不提供保证,请勿随意复制。)

1. 在应用程序启动时注册一个 URI 处理程序

您可以通过HKEY_CURRENT_USER/Software/Classes在 Windows 注册表中的(因此不需要管理员权限)键中创建一个键来注册 URI-Handler

  • 键的名称等于 URI 前缀,badcompany在我们的例子中
  • 该键包含一个名为的空字符串值 URL Protocol
  • 键包含DefaultIcon图标的子键(其实我也不知道有没有必要),我用的是当前可执行文件的路径
  • 有一个子键shell/open/command,它的默认值决定了尝试打开 URI 时要执行的命令的路径,**请注意*,"%1"必须将 URI 传递给可执行文件
    this.EnsureKeyExists(Registry.CurrentUser, "Software/Classes/badcompany", "URL:BadCo Applications");
    this.SetValue(Registry.CurrentUser, "Software/Classes/badcompany", "URL Protocol", string.Empty);
    this.EnsureKeyExists(Registry.CurrentUser, "Software/Classes/badcompany/DefaultIcon", $"{location},1");
    this.EnsureKeyExists(Registry.CurrentUser, "Software/Classes/badcompany/shell/open/command", $"\"{location}\" \"%1\"");

// ...

private void SetValue(RegistryKey rootKey, string keys, string valueName, string value)
{
    var key = this.EnsureKeyExists(rootKey, keys);
    key.SetValue(valueName, value);
}

private RegistryKey EnsureKeyExists(RegistryKey rootKey, string keys, string defaultValue = null)
{
    if (rootKey == null)
    {
        throw new Exception("Root key is (null)");
    }

    var currentKey = rootKey;
    foreach (var key in keys.Split('/'))
    {
        currentKey = currentKey.OpenSubKey(key, RegistryKeyPermissionCheck.ReadWriteSubTree) 
                     ?? currentKey.CreateSubKey(key, RegistryKeyPermissionCheck.ReadWriteSubTree);

        if (currentKey == null)
        {
            throw new Exception("Could not get or create key");
        }
    }

    if (defaultValue != null)
    {
        currentKey.SetValue(string.Empty, defaultValue);
    }

    return currentKey;
}
Run Code Online (Sandbox Code Playgroud)

2.为IPC打开一个管道

由于您必须将消息从程序的一个实例传递到另一个实例,因此您必须打开一个可用于该目的的命名管道。

我在后台循环调用此代码 Task

private async Task<string> ReceiveTextFromPipe(CancellationToken cancellationToken)
{
    string receivedText;

    PipeSecurity ps = new PipeSecurity();
    System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
    PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
    ps.AddAccessRule(par);

    using (var pipeStream = new NamedPipeServerStream(this._pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 4096, 4096, ps))
    {
        await pipeStream.WaitForConnectionAsync(cancellationToken);

        using (var streamReader = new StreamReader(pipeStream))
        {
            receivedText = await streamReader.ReadToEndAsync();
        }
    }

    return receivedText;
}
Run Code Online (Sandbox Code Playgroud)

3.确保应用程序只启动一次

这可以使用Mutex.

internal class SingleInstanceChecker
{
    private static Mutex Mutex { get; set; }

    public static async Task EnsureIsSingleInstance(string id, Action onIsSingleInstance, Func<Task> onIsSecondaryInstance)
    {
        SingleInstanceChecker.Mutex = new Mutex(true, id, out var isOnlyInstance);
        if (!isOnlyInstance)
        {
            await onIsSecondaryInstance();
            Application.Current.Shutdown(0);
        }
        else
        {
            onIsSingleInstance();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当互斥量已被另一个实例获取时,应用程序并未完全启动,而是

4. 处理使用身份验证重定向 URI 调用

  1. 如果它是唯一的(第一个)实例,它可以自己处理身份验证重定向 URI
    • 从 URI 中提取令牌
    • 存储令牌(如有必要和/或需要)
    • 将令牌用于请求
  2. 如果是进一步的例子
    • 使用管道将重定向 URI 传递给第一个实例
    • 第一个实例现在执行1下的步骤
    • 关闭第二个实例

URI 被发送到第一个实例

internal class SingleInstanceChecker
{
    private static Mutex Mutex { get; set; }

    public static async Task EnsureIsSingleInstance(string id, Action onIsSingleInstance, Func<Task> onIsSecondaryInstance)
    {
        SingleInstanceChecker.Mutex = new Mutex(true, id, out var isOnlyInstance);
        if (!isOnlyInstance)
        {
            await onIsSecondaryInstance();
            Application.Current.Shutdown(0);
        }
        else
        {
            onIsSingleInstance();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)