【问题标题】:oAuth 2.0 API Consumption via C#oAuth 2.0 API 使用 C#
【发布时间】:2016-10-22 09:22:45
【问题描述】:

我们的客户需要将他们的 API 与我们为他们开发的网站集成。 API 身份验证是通过 oAuth 2.0 完成的。他们提供了所有必要的信息(客户端 ID、客户端密码、令牌 Uri 等)。

但是,我们很难理解通过 C# 调用它的代码 sn-p。我们知道我们必须请求一个请求令牌并将其附加到后续请求的标头中。我们尝试了 DotNetOpenAuth 和 Owin,但无法找到实现这个的实际代码/到目前为止没有成功。 谁能帮我用一小段 C# 代码来实现这一点?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api oauth-2.0


    【解决方案1】:
    using(var client = new HttpClient()) 
    {
       var postData = new List<KeyValuePair<string, string>>();
                postData.Add(new KeyValuePair<string, string> 
                                                      ("grant_type",clientcredentials));
                postData.Add(new KeyValuePair<string, string>("client_id", clientId));
                postData.Add(new KeyValuePair<string, string>("client_secret", 
                                                                   clientSecret));
    
                HttpContent content = new FormUrlEncodedContent(postData);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www- 
                                                                     form-urlencoded");
                client.DefaultRequestHeaders.Authorization = new 
                            AuthenticationHeaderValue("Basic", yourauthvalue);
    
                var responseResult = client.PostAsync(oauthUrl, content).Result;
    
    }
    

    【讨论】:

    • 你的authvalue可以通过使用postman测试oauth2请求得到
    【解决方案2】:

    要请求访问令牌,您只需要发布身份验证数据的请求。此代码已使用资源所有者密码凭据授权从工作 MVC 应用程序中提取:

    using (var client = new HttpClient())
    {
        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("username", _user));
        postData.Add(new KeyValuePair<string, string>("password", _pwd));
        postData.Add(new KeyValuePair<string, string>("grant_type", "password"));
        postData.Add(new KeyValuePair<string, string>("client_id", _clientId));
        postData.Add(new KeyValuePair<string, string>("client_secret", _clientSecret));
    
        HttpContent content = new FormUrlEncodedContent(postData);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
    
        var responseResult = client.PostAsync(_tokenUrl, content).Result;
    
        return responseResult.Content.ReadAsStringAsync().Result;
    }
    

    希望对你有帮助。

    编辑

    这里有一段代码 sn-p 刷新令牌:

    using (var client = new HttpClient())
    {
        var postData = new List<KeyValuePair<string, string>>();
        postData.Add(new KeyValuePair<string, string>("refresh_token", _refreshToken));
        postData.Add(new KeyValuePair<string, string>("grant_type", "refresh_token"));
        postData.Add(new KeyValuePair<string, string>("client_id", _clientId));
        postData.Add(new KeyValuePair<string, string>("client_secret", _clientSecret));
    
        HttpContent content = new FormUrlEncodedContent(postData);
        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
    
        var responseResult = client.PostAsync(_tokenUrl, content).Result;
    
        return responseResult.Content.ReadAsStringAsync().Result;
    }
    

    并使用它:

    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
        HttpResponseMessage result = client.GetAsync(_url).Result;
    
        if (result.StatusCode == HttpStatusCode.Unauthorized)
        {
            RefreshToken(); /* Or reenter resource owner credentials if refresh token is not implemented */
            if (/* token refreshed, repeat the request using the new access token */)
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _newAccessToken);
    
                result = client.GetAsync(_url).Result;
    
                if (result.StatusCode == HttpStatusCode.Unauthorized)
                {
                    // Process the error
                }
            }
        }
    
        return result;
    }
    

    【讨论】:

    • 谢谢!看来我现在可以检索令牌(稍作修改,例如添加“范围”等)。在我将其标记为答案之前的最后一个问题。因此,将令牌与后续请求附加在一起就可以了。但是想知道是否应该每次都生成令牌,或者 C# 是否会处理相同的令牌直到它过期,并且只有在它过期后才重新生成。更好的方法是什么?任何代码示例将不胜感激!
    • 您必须附加相同的令牌,直到您获得 401 - 未经授权的响应,然后如果您的授权服务器实现此功能,则无论是发布资源所有者凭据还是使用刷新令牌,您都需要获取新的访问令牌.刷新令牌授予请求类似于凭证之一,但对用户是透明的,不需要重新输入他们的凭证。请使用新代码 sn-p 查看编辑后的响应。
    • 谢谢。我一直在玩这个。所以我明白,我们需要为每个会话生成密钥,如果密钥过期,我们将在会话期间刷新令牌。这也意味着,如果用户关闭浏览器并稍后返回,则在他开始使用 api 时将生成令牌。对吗?
    • 如果将令牌保存在会话中,则取决于会话的持久性。考虑到如果会话在令牌之前过期,您将需要在创建新会话时请求新令牌。
    猜你喜欢
    • 2020-07-22
    • 2015-08-25
    • 2015-01-15
    • 2015-11-11
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    相关资源
    最近更新 更多