DotNetOpenAuth 谷歌 OAuth2

2023-12-26

在最后一个DotNetOpenAuth包中,GoogleClient扩展了OpenIdClient,有人知道我在哪里可以找到扩展DotNetOpenAuth OAuth2Client的google Oauth2的实现?


From OAuth2 和 DotNetOpenAuth - 实现 Google 自定义客户端 https://stackoverflow.com/questions/13727466/oauth2-and-dotnetopenauth-implementing-google-custom-client

public class GoogleOAuth2Client : OAuth2Client
{
    #region Constants and Fields

    /// <summary>
    /// The authorization endpoint.
    /// </summary>
    private const string AuthorizationEndpoint = "https://accounts.google.com/o/oauth2/auth";

    /// <summary>
    /// The token endpoint.
    /// </summary>
    private const string TokenEndpoint = "https://accounts.google.com/o/oauth2/token";

    /// <summary>
    /// The _app id.
    /// </summary>
    private readonly string _clientId;

    /// <summary>
    /// The _app secret.
    /// </summary>
    private readonly string _clientSecret;

    #endregion

    public const string ProviderAppendix = "__provider__=google";

    public GoogleOAuth2Client(string clientId, string clientSecret)
        : base("google")
    {
        if (string.IsNullOrWhiteSpace(clientId)) throw new ArgumentNullException("clientId");
        if (string.IsNullOrWhiteSpace(clientSecret)) throw new ArgumentNullException("clientSecret");

        this._clientId = clientId;
        this._clientSecret = clientSecret;
    }

    protected override Uri GetServiceLoginUrl(Uri returnUrl)
    {
        StringBuilder serviceUrl = new StringBuilder();

        serviceUrl.AppendFormat("{0}?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile", AuthorizationEndpoint);
        serviceUrl.Append("&state=google");
        serviceUrl.AppendFormat("&redirect_uri={0}", returnUrl.ToString().ToLower());
        serviceUrl.Append("&response_type=code");
        serviceUrl.AppendFormat("&client_id={0}", _clientId);

        return new Uri(serviceUrl.ToString());
    }

    protected override IDictionary<string, string> GetUserData(string accessToken)
    {
        var client = new RestClient("https://www.googleapis.com");
        var request = new RestRequest(String.Format("/oauth2/v1/userinfo?access_token={0}", accessToken), Method.GET);
        IDictionary<String, String> extraData = new Dictionary<String, String>();

        var response = client.Execute(request);
        if (null != response.ErrorException)
        {
            return null;
        }
        else
        {
            try
            {
                var json = JObject.Parse(response.Content);

                string firstName = (string)json["given_name"];
                string lastName = (string)json["family_name"];
                string emailAddress = (string)json["email"];
                string id = (string)json["id"];

                extraData = new Dictionary<String, String>
            {
                {"accesstoken", accessToken}, 
                {"name", String.Format("{0} {1}", firstName, lastName)},
                {"firstname", firstName},
                {"lastname", lastName},
                {"email", emailAddress},
                {"id", id}                                           
            };
            }
            catch (Exception ex)
            {
                Ccl.Log.Logging.Error("Error requesting OAuth user data from Google", ex);
                return null;
            }

            return extraData;
        }
    }

    protected override string QueryAccessToken(Uri returnUrl, string authorizationCode)
    {
        StringBuilder postData = new StringBuilder();
        postData.AppendFormat("client_id={0}", this._clientId);
        postData.AppendFormat("&redirect_uri={0}", HttpUtility.UrlEncode(returnUrl.ToString().ToLower()));
        postData.AppendFormat("&client_secret={0}", this._clientSecret);
        postData.AppendFormat("&grant_type={0}", "authorization_code");
        postData.AppendFormat("&code={0}", authorizationCode);

        string response = "";
        string accessToken = "";

        var webRequest = (HttpWebRequest)WebRequest.Create(TokenEndpoint);

        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";

        try
        {

            using (Stream s = webRequest.GetRequestStream())
            {
                using (StreamWriter sw = new StreamWriter(s))
                    sw.Write(postData.ToString());
            }

            using (WebResponse webResponse = webRequest.GetResponse())
            {
                using (var reader = new StreamReader(webResponse.GetResponseStream()))
                {
                    response = reader.ReadToEnd();
                }
            }

            var json = JObject.Parse(response);
            accessToken = (string)json["access_token"];
        }
        catch (Exception ex)
        {
            Ccl.Log.Logging.Error("Error requesting OAuth access token from Google", ex);
            return null;
        }

        return accessToken;
    }

    public override AuthenticationResult VerifyAuthentication(HttpContextBase context, Uri returnPageUrl)
    {
        string code = context.Request.QueryString["code"];
        if (string.IsNullOrEmpty(code))
        {
            return AuthenticationResult.Failed;
        }

        string accessToken = this.QueryAccessToken(returnPageUrl, code);
        if (accessToken == null)
        {
            return AuthenticationResult.Failed;
        }

        IDictionary<string, string> userData = this.GetUserData(accessToken);
        if (userData == null)
        {
            return AuthenticationResult.Failed;
        }

        string id = userData["id"];
        string name;

        // Some oAuth providers do not return value for the 'username' attribute. 
        // In that case, try the 'name' attribute. If it's still unavailable, fall back to 'id'
        if (!userData.TryGetValue("username", out name) && !userData.TryGetValue("name", out name))
        {
            name = id;
        }

        // add the access token to the user data dictionary just in case page developers want to use it
        userData["accesstoken"] = accessToken;

        return new AuthenticationResult(
            isSuccessful: true, provider: this.ProviderName, providerUserId: id, userName: name, extraData: userData);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

DotNetOpenAuth 谷歌 OAuth2 的相关文章

随机推荐

  • 定义海报属性和预加载时视频消失

    我有一个具有以下属性的视频标签
  • Play Framework 2.5如何添加mongoDB?

    我想在我的 Play Framework 2 5 应用程序中添加 MongoDB 我们可以看到这个模块here https www playframework com modules mongo 1 1 home aEnabletheMon
  • HTML 中具有多层 SVG 的交互式地图

    我正在开发一个门户网站 其中包含多层地图 例如城市 河流 各种地理区域的名称等 但对于如何进行门户网站的开发 我遇到了一个困境 我将尝试简单地解释一下这个问题 地图的基本信息 地图必须是交互式的 缩放功能 弹出框 通过单击或悬停鼠标来更改元
  • 按功能打包的方法好吗? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 最近我发现了这个 javalobby 帖子http java dzone com articles how chang java package
  • 来自 .csv,只读或分成由“”分隔的部分

    我有一个 csv 文件 该文件分为多个部分 每个部分都以 开头 各占一行 如本例所示 接下来是一组列及其各自的值行 各部分之间的列不一致 lt section1 gt br col1 col2 col3 br val1 val2 val3
  • Linq - 按 StartsWith 排序然后包含

    假设我有 3 个客户姓名 Microsoft Another customer also called Microsoft A third customer called Microsoft 现在 如果我像这样查询客户 var q from
  • 尽快通过 Visual Studio 查找搁置集

    我每天需要使用 Visual Studio 查看许多架子集 我已经添加了TfsPendingChanges命令到我的工具栏 但访问搁置集的其余过程 操作 查找搁置集 仍然感觉很笨拙 事实上 搁置集审查与我自己的待定更改无关 VS11 只是让
  • C++如何处理&&? (短路评估)[重复]

    这个问题在这里已经有答案了 当遇到 bool1 bool2 时 c 是否会尝试检查 bool2 是否发现 bool1 为 false 还是会像 PHP 那样忽略它 抱歉 如果这个问题太基础了 但我确实在 Schildt 和互联网上都找不到提
  • 我可以在 C# 中创建非静态 Azure 函数类,会有什么后果?

    Azure 函数中的构造函数注入和自定义遥测事件的集合需要此非静态类 如果我们在 Visual Studio 中创建一个 Azure 函数应用程序 它会使用 static 关键字创建默认值 如下所示 public static async
  • 使用 javascript 将按钮添加到现有 DIV

    在我的页面上有 div div 我想使用 JS 将这种类型的 按钮 附加到它 a href news events span class picon p add news span Read more news a 我尝试使用 docume
  • 我的 Laravel 应用程序在 Google Cloud 上出现问题。无法打开流或文件“/srv/storage/logs/laravel.log”

    Laravel 应用程序在我的本地运行良好 但是当我使用命令将其上传到 Google App Engine 时gcloud app deploy 然后它给我写日志时出错 UnexpectedValueException The stream
  • 如何在 Vim 中正确扩展突出显示组?

    我想创建一个名为的突出显示组Italic完全像Normal但文本为斜体 目前 我的Normal突出显示 被设定为 ctermfg 251 ctermbg 234 guifg cccccc guibg 242424 我的问题是 正在添加ter
  • Python 3.4-定期插入空格[重复]

    这个问题在这里已经有答案了 我试图让 Python 允许我在字符串中定期插入一个空格 每 5 个字符 这是我的代码 str1 abcdefghijklmnopqrstuvwxyz list1 list2 count 3 space conv
  • 处理凌乱的日期

    我希望你没有认为我是在寻求感情方面的建议 有时 我必须向调查受访者提供指定事件发生时间的能力 结果是一个非常混乱的字符串 老实说我不知道 该怎么处理 超越手工重新编码 这是一个简短的样本 有数千个 c May2 12 noon 9 45 a
  • Python UDP套接字半随机接收失败

    我遇到了一些问题 我猜是代码问题 该应用程序用于 ping 一些定制的网络设备 以检查它们是否处于活动状态 它每 20 秒使用一个特殊的 UDP 数据包对它们执行 ping 操作 并期望得到响应 如果他们连续 3 次未能应答 ping 应用
  • C++ 两个阶乘之和等于 10 的阶乘找到两个值 x 和 y,其阶乘之和[关闭]

    Closed 这个问题需要细节或清晰度 help closed questions 目前不接受答案 我陷入了一个简单的 C 问题 但这对我来说现在很困难 谁能帮我解决这个问题 我已经为这个问题编写了 C 代码 我知道代码无法作为问题的答案打
  • 如何在 matplotlib 中向水平条形图添加标签?

    如何在 matplotlib 中向水平条形图添加标签 大家好 我是 matplotlib 和 python 新手 我想再次问这个问题以获得一些帮助 看看是否有比我找到的当前解决方案更简单的方法来为每个条形表示的计数添加标签 这是我写的代码
  • 如何选择具有特定属性的所有元素?使用 TinyXPath

    用于选择具有属性 A 的所有元素的 XPath 表达式是什么 const char xpath A 此 XPath 选择具有 A 属性的所有元素 A
  • 如何通过PHP和mysql构建无限级菜单

    好吧 为了构建我的菜单 我使用类似数据库的结构 如下所示 2 Services 0 3 Photo Gallery 0 4 Home 0 5 Feedback 0 6 FAQs 0 7 News Events 0 8 Testimonial
  • DotNetOpenAuth 谷歌 OAuth2

    在最后一个DotNetOpenAuth包中 GoogleClient扩展了OpenIdClient 有人知道我在哪里可以找到扩展DotNetOpenAuth OAuth2Client的google Oauth2的实现 From OAuth2