【问题标题】:Google Oauth 2 get access token and refresh token from authorization codeGoogle Oauth 2 从授权码中获取访问令牌和刷新令牌
【发布时间】:2015-02-24 20:18:51
【问题描述】:

我在 javascript 的帮助下获得了授权码。现在在服务器上,我需要刷新令牌作为交换。这是我的代码。

    byte[] buffer = Encoding.ASCII.GetBytes("code=" + "....."
        + "&client_id=.....&client_secret=...&redirect_uri=https%3A%2F%2Fmysite.com%2Fportal%2F&grant_type=authorization_code");
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");

    req.Method = "POST";
    req.ContentType = "application/x-www-form-urlencoded";
    req.ContentLength = buffer.Length;

    Stream strm = req.GetRequestStream();
    strm.Write(buffer, 0, buffer.Length);
    strm.Close();

    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

它引发异常Bad request,内部异常为空。

更新:

我在 ASP.NET MVC 4 应用程序中使用它。由于是异步操作,所以我切换到Visual Studio 2013。我修改了代码await

UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                        new[] { 
                        GmailService.Scope.GmailCompose, GmailService.Scope.GmailModify, GmailService.Scope.GmailReadonly
                        },
                    "user", 
                    CancellationToken.None
                    ) ;

在此语句中,它会挂起浏览器(类似于this 问题)。我试过放日志,没有异常,也没有进一步执行。

【问题讨论】:

    标签: javascript c# oauth oauth-2.0 google-oauth


    【解决方案1】:

    Google 身份验证的第一步是响应类型代码。它是一个 HTTP GET,基本上只是打开一个新的浏览器窗口。一旦用户接受您的身份验证,他们就会获得一个身份验证代码,然后他们必须将其带回您的应用程序。它也出现在浏览器标题中。

    https://accounts.google.com/o/oauth2/auth?client_id={clientid}.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code
    

    所有三个步骤的完整说明可以在这里找到Google 3 legged oauth2

    我不确定我是否理解您为什么要这样做。使用 Google .net 客户端库要容易得多。 NuGet Google Client lib 我不确定您打算访问哪个 API,但使用 nuget 谷歌它,您应该找到要安装的正确库。

    【讨论】:

    • 谢谢。只有在您的文章 (daimto.com/google-oauth2-csharp) 的帮助下,我才能从服务器端做到这一点。我有一个疑问......我们可以控制用户授权的完成方式吗?喜欢显示弹出窗口而不是全新的浏览器选项卡?还是我们无法控制?
    • 有没有办法获得离线访问令牌?我需要保留刷新令牌并在之后使用它。
    • 您需要自己实现 iDatastore 以将其保存到 filedatastore 将其存储到 %appdata%
    • 我将它存储在我的数据库中。但是当我在工作后使用刷新令牌获取访问令牌时,它不起作用。
    • 你可以在这里找到一个 db 的例子github.com/LindaLawton/Google-Dotnet-Samples/tree/master/…
    猜你喜欢
    • 2019-03-16
    • 2016-10-13
    • 2018-06-23
    • 2015-10-11
    • 2015-11-26
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 2013-09-05
    相关资源
    最近更新 更多