【问题标题】:How to get the userId parameter to call ExchangeCodeForTokenAsync如何获取 userId 参数以调用 ExchangeCodeForTokenAsync
【发布时间】:2015-02-08 23:13:46
【问题描述】:

我正在开发一个调用 .NET 应用程序的 Chrome 扩展程序。在那个 .NET 应用程序中,我使用 Gmail API 来管理和阅读登录用户的电子邮件。

我遵循了 Google 提供的 .NET API 示例here。在那个例子中,有一个像这样声明的局部变量:

    // Application logic should manage users authentication. 
    // This sample works with only one user. You can change
    // it by retrieving data from the session.
    private const string UserId = "user-id";

并且有很多方法使用这个变量作为参数:

var oauthState = AuthWebUtility.ExtracRedirectFromState( flow.DataStore, UserId,...

var token = flow.ExchangeCodeForTokenAsync(UserId,...

var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId,...

我的问题是:如何获取 UserId?我应该从会话中得到它吗?我应该从 chrome.storage 的某个地方获取它吗?

【问题讨论】:

    标签: .net google-chrome-extension google-oauth gmail-api


    【解决方案1】:

    您可以从会话中获取用户 ID。这是相同的link

    public override string GetUserId(Controller controller)
        {
                 // In this sample we use the session to store the user identifiers.
                // That's not the best practice, because you should have a logic to identify
               // a user. You might want to use "OpenID Connect".
            // You can read more about the protocol in the following link:
            // https://developers.google.com/accounts/docs/OAuth2Login.
            var user = controller.Session["user"];
            if (user == null)
            {
                user = Guid.NewGuid();
                controller.Session["user"] = user;
            }
            return user.ToString();
    
        }
    

    但是,最佳做法是使用Google+ sign in 进行身份验证。当用户登录时,您会获得一个 OAuth 令牌,用于代表他们发出 API 请求,您可以使用它来更好地了解您的用户。如果您有任何问题,请告诉我。

    【讨论】:

    • 抱歉,我必须取消将问题标记为已解决。 GetUserId方法不起作用,因为它每次都会获得不同的用户。我将尝试使用 Google+ 方法,但我必须对我的代码进行大量更改。
    • 此外,文档不是很有用 如何设置阅读和管理电子邮件的权限?如何将令牌传递给服务器?
    【解决方案2】:

    我最近也在努力。

    确保您在第一次重定向到 Google 时包含正确的范围:

    https://www.googleapis.com/auth/userinfo.profile
    https://www.googleapis.com/auth/userinfo.email
    

    然后你只需要为它声明一个类似的字符串

    private const string UserId = "user-id";
    

    我不确定这是否是一个正确的解决方案, 但它在我的项目中工作

    仅供参考。

    顺便问一下,用token连接服务器的问题你解决了吗?

    如果您对我有什么好的建议,不胜感激,谢谢。

    【讨论】:

    • 使用唯一的用户 ID 不适用于多用户应用程序。关于令牌:我得出的结论是,Google+ 方法仅适用于 Javascript 应用程序,不适用于服务器端应用程序。目前,我正在从客户端手动获取用户并通过 POST 方法发送到服务器。
    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多