代码之家  ›  专栏  ›  技术社区  ›  Robert Thompson

从使用OAuth2进行身份验证时,无法从重定向url获取身份验证代码。NET桌面应用程序

  •  0
  • Robert Thompson  · 技术社区  · 1 年前

    我正在尝试在中创建桌面应用程序。NET,允许用户使用OAuth2登录。但是,我永远无法从重定向url中获取上下文。当我启动该过程时,我能够访问身份验证url,点击身份验证按钮会将我发送到带有访问令牌的重定向url,但我无法在代码中使用它,而这正是需要使用它的地方。有人能帮帮我,告诉我我做错了什么吗?

    public class Authenticate
    {
        private Browser _browser;
    
        public async Task AuthenticateUser()
        {
            _browser = new();
    
            string redirect = "https://localhost:7270/discord/auth";
            string url = "https://discord.com/oauth2/authorize?response_type=code&client_id={MyClientId}&scope={MyScopes}&redirect_uri={HttpUtility.UrlEncode(redirectUrl)}";
    
            BrowserOptions options = new(url, "https://localhost:7270/");
    
            BrowserResult result = await _browser.InvokeAsync(options, default);
        }
    }
    
    public class Browser : IBrowser
    {
        public async Task<BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken)
        {
            Process.Start(new ProcessStartInfo(options.StartUrl) { UseShellExecute = true, });
    
            var result = new BrowserResult();
    
            using(var listener = new HttpListener())
            {
                var listenUrl = options.EndUrl;
    
                listener.Prefixes.Add(listenUrl);
                listener.Start();
    
                try
                {
                    var context = await listener.GetContextAsync();
    
                    result.Response = context.Request.Url.AbsoluteUri;
    
                    return result;
                }
                catch(Exception ex)
                {
                    return result;
                }
            }
        }
    }
    

    发生的事情是,它将运行到试图获取监听器上下文的行,然后旋转。不会抛出异常,不会命中断点,也不会返回任何内容。

    正如您从下面的图片中看到的,授权和重定向url都按预期工作。但是,我的代码需要重定向url中的代码查询参数,这是我无法获得的。

    Auth endpoint

    Redirect

    提前感谢

    0 回复  |  直到 1 年前
        1
  •  0
  •   Gary Archer    1 年前

    您的代码看起来基本正确,除了在监听环回响应时应该使用纯HTTP URL。为这种类型的连接设置TLS和管理证书是不切实际的。

    被拦截的授权码应受到PKCE机制的保护。如果授权服务器支持,您可以更新代码以使用它。有关这些主题的更多信息,请参阅 RFC 8252 document .