【问题标题】:Getting information with Token. OAuth使用 Token 获取信息。身份验证
【发布时间】:2011-10-06 11:31:17
【问题描述】:

我正在创建一个应用程序以使用 OAuth 从 Fitbit.com 获取信息。

protected void btnConnect_Click(object sender, EventArgs e)
    {
        // Create OAuthService object, containing oauth consumer configuration
        OAuthService service = OAuthService.Create(
            new EndPoint(RequestTokenUrl, "POST"),         // requestTokenEndPoint
            new Uri(AuthorizationUrl),                     // authorizationUri
            new EndPoint(AccessTokenUrl, "POST"),          // accessTokenEndPoint
            true,                                          // useAuthorizationHeader
            "http://app.fitbit.com",                       // realm
            "HMAC-SHA1",                                   // signatureMethod
            "1.0",                                         // oauthVersion
            new OAuthConsumer(ConsumerKey, ConsumerSecret) // consumer
            );

        try
        {
            var personRepository = new PersonRepository();

            var person = personRepository.GetPersonById(int.Parse(personSelect.SelectedItem.Value));



            OAuthRequest request = OAuthRequest.Create(
                new EndPoint(ProfileUrl, "GET"),
                service,
                this.Context.Request.Url,
                //this.Context.Session.SessionID);
                person.FitbitAuthAccessToken,
                );

            request.VerificationHandler = AspNetOAuthRequest.HandleVerification;

            OAuthResponse response = request.GetResource();

            // Check if OAuthResponse object has protected resource
            if (!response.HasProtectedResource)
            {
                var token = new OAuthToken(TokenType.Request, person.FitbitAuthAccessToken,
                    person.FitbitAuthSecret, ConsumerKey);
                // If not we are not authorized yet, build authorization URL and redirect to it
                string authorizationUrl = service.BuildAuthorizationUrl(response.Token).AbsoluteUri;
                Response.Redirect(authorizationUrl);
            }


            person.FitbitAuthAccessToken = response.Token.Token;
            person.FitbitAuthSecret = response.Token.Secret;
            person.PersonEncodedId = Doc["result"]["user"]["encodedId"].InnerText;
            personRepository.Update(person);

            // Store the access token in session variable
            Session["access_token"] = response.Token;
        }
        catch (WebException ex)
        {
            Response.Write(ex.Message);
            Response.Close();
        }
        catch (OAuthRequestException ex)
        {
            Response.Write(ex.Message);
            Response.Close();
        }
    }

我将 Fitbit 访问令牌和秘密保存在数据库中。
如何仅使用访问令牌和密钥获取信息,而无需每次都授权?

【问题讨论】:

    标签: c# .net oauth


    【解决方案1】:

    这将假设 FitBit api 足够强大,不会每次都进行身份验证。我已经看到 API 实现 OAuth,你有一个身份验证过程,然后从那里你的大多数调用只需要 AccessToken 或秘密。我会查看服务的方法签名,看看它们需要什么类型的参数。

    【讨论】:

    • 可以说他们每次都不需要身份验证有没有办法使用 OAuth 库从我上次登录时传递令牌?我看不到任何允许这样做的 OAuthRequest.Create 覆盖。
    • 您需要注册一次(当您第一次为每个用户设置时)。之后,您存储访问令牌并在访问 API 时在 OAuth 标头中使用它。
    • 能否举个例子,使用.net oauth 库将其存储在标头中!
    • FitBit 的OAuth .Net 示例中,您可以看到创建OAuthService 时,需要将useAuthorizationHeader 设置为true。当您通过 service.BuildAuthorizationUrl 调用访问资源时,它会将 oAuth 信息放在 header 中。
    【解决方案2】:

    如果您查看有关身份验证和访问资源的FitBit API,您会发现您只需要请求您感兴趣的数据并在 oAuth 标头中添加访问令牌即可。下面是它的样子(来自 API 页面):

    GET /1/user/-/activities/date/2010-04-02.json HTTP/1.1
    Host: api.fitbit.com
    Authorization: OAuth realm="api.fitbit.com",
    oauth_consumer_key="fitbit-example-client-application",
    oauth_token="8d3221fb072f31b5ef1b3bcfc5d8a27a",
    oauth_signature_method="HMAC-SHA1",
    oauth_timestamp="1270248088",
    oauth_nonce="515379974",
    oauth_signature="Gf5NUq1Pvg3DrtxHJyVaMXq4Foo%3D"
    oauth_version="1.0"`
    

    基本签名字符串如下所示:

    GET&http%3A%2F%2Fapi.fitbit.com%2F1%2Fuser%2F-%2Factivities%2Fdate%2F2010-04-02.json&oauth_consumer_key%3Dfitbit-example-client-application%26oauth_nonce%3D515379974%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1270248088%26oauth_token%3D8d3221fb072f31b5ef1b3bcfc5d8a27a%26oauth_version%3D1.0
    

    【讨论】:

    • 如何使用 OAuth 库实现这一点?
    【解决方案3】:

    我想我会提供我的 VerifyAuthenticationCore,它是我的 FitbitClient 的一部分,它继承自 OAuthClient。我花了一段时间才让这个工作,但我发现我在创建 Web 请求时缺少 HttpDeliveryMethods.AuthorizationHeaderRequest。添加此项允许调用停止返回错误请求 (400) 错误消息。

    下面的代码基本上是使用用户 id 和访问令牌来获取用户配置文件信息。所有调用基本上都应该以这种方式工作。您需要做的就是更改 url 并提供 id 和 token。

    protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response)
        {
            string username;
            var accessToken = response.AccessToken;
            var userId = response.ExtraData["encoded_user_id"];
            var httpWebRequest = WebWorker.PrepareAuthorizedRequest(new MessageReceivingEndpoint(new Uri("http://api.fitbit.com/1/user/" + userId + "/profile.json"), HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), accessToken);
            var dictionary = new Dictionary<string, string>();
            dictionary.Add("accesstoken", accessToken);
            dictionary.Add("link", "http://www.fitbit.com/user/" + userId);
    
            using (var webResponse = httpWebRequest.GetResponse())
            {
                using (var stream = webResponse.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    var profile = JObject.Parse(reader.ReadToEnd())["user"];
                    dictionary.AddItemIfNotEmpty("name", profile["displayName"]);
                    dictionary.AddItemIfNotEmpty("pictureUrl", profile["avatar"]);
                    username = dictionary["name"];
                }
            }
    
            return new AuthenticationResult(true, ProviderName, userId, username, dictionary);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-29
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多