oauth2.0 在基于C# Windows的应用程序中从URL阅读授权代码时需要帮助

roejwanj  于 2023-02-11  发布在  C#
关注(0)|答案(1)|浏览(160)

我正在尝试使用C#在基于Windows的应用程序中实现oAuth2(这是非常直接的Web应用程序)。
我很难从返回/重定向的URL中读取代码
以下是步骤顺序
通过单击URL https://{服务器}/auth/oauth2/authorize获取授权码?响应类型=代码&客户端ID =客户端ID} &作用域=用户&重定向URI = http://本地主机&状态= 123456789
注意:当我们点击上述URL时,它会在内部重定向到本地ADFS服务器(类似于https://adfsserver/...),并将SAML令牌发送回{Server},{Server}将验证令牌并生成以下格式的授权代码
本地主机/?代码= JSgTYUHfrIO6pHA8ha5Z55MDuC8bEl1K和状态= 123456789
现在我需要从上面的URL读取代码值。
我尝试在C#中使用WebBrowser控件,但不幸的是,它捕获了发生在ADFS服务器上的初始重定向,即捕获URL https://adfsserver/...。
任何人都可以请指导我如何捕获目标网址的代码?
注意:我再次尝试从控制台/Windows/WPF应用程序实现这一点。
先谢谢你。
使用WebBrowser控件但不成功

this._uri = $"https://{_Server}/auth/oauth2/authorize?response_type=code&client_id={_ClientId}&scope=user&redirect_uri=http://localhost&state=123456789";

            this._browser = new System.Windows.Forms.WebBrowser();
            this._browser.Navigated += new WebBrowserNavigatedEventHandler(browser_Navigated);
            this._browser.Navigate(this._uri);
r6hnlfcb

r6hnlfcb1#

我就是这样做到的

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Web;
using System.Windows.Forms;

namespace OAuthDMS.App_Code.RestApi
{
    internal class Authorization_Code
    {
        private static string _AuthCode = "";
        private static string _State = "";
        private static WebBrowser _WebBrowser = null;

        internal void AuthorizationCodeLogin()
        {
            // Force TLS 1.2 instead of the default value.
            ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            //Auth code url
            string _AuthCodeUri = $"https://{Properties.Server}/auth/oauth2/authorize?response_type=code&client_id={Properties.ClientId}&scope=user&redirect_uri=http://localhost&state=123456789";
            
            //first get authorization code
            _WebBrowser = new WebBrowser();
            _WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(GetAuthorizationCode);
            _WebBrowser.Url = new Uri(_AuthCodeUri);
        }

        private void GetAuthorizationCode(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (e.Url.AbsolutePath.Equals("/"))
            {
                _AuthCode = HttpUtility.ParseQueryString(e.Url.Query).Get("code");
                _State = HttpUtility.ParseQueryString(e.Url.Query).Get("state");

                if (_AuthCode != null && _State == "123456789")
                {
                    OAuth2();
                }
            }
        }

        private async void OAuth2()
        {
            //login url
            string _OAuth2Uri = $"https://{Properties.Server}/auth/oauth2/token";

            //Holds authentication token details (on success)
            AuthenticationToken _WorkAuthToken = null;

            //Authenticating into DMS using password grant
            Dictionary<string, string> _RequestBody = new()
            {
                { "grant_type", "authorization_code" },
                { "client_id", Properties.ClientId },
                { "client_secret", Properties.ClientSecret },
                { "code", _AuthCode },
                { "redirect_uri", "http://localhost" }
            }; 
            
            using (HttpClient _HttpClient = new())
            {
                using (HttpRequestMessage _HttpReqMsg = new(HttpMethod.Post, _OAuth2Uri))
                {
                    _HttpReqMsg.Content = new FormUrlEncodedContent(_RequestBody);

                    using (HttpResponseMessage _HttpResMsg = await _HttpClient.SendAsync(_HttpReqMsg))
                    {
                        if (_HttpResMsg.StatusCode == HttpStatusCode.OK)
                        {
                            _WorkAuthToken = JsonSerializer.Deserialize<AuthenticationToken>(_HttpResMsg.Content.ReadAsStringAsync().Result);
                        }
                    }
                }
            }

            MessageBox.Show(_WorkAuthToken.access_token);
        }

        public class AuthenticationToken
        {
            public string access_token { get; set; }
            public string token_type { get; set; }
            public string scope { get; set; }
            public string refresh_token { get; set; }
            public int expires_in { get; set; }
        }
    }
}

相关问题