通过C#oAuth 2.0 API消耗

My *_*per 1 c# asp.net-mvc oauth-2.0 asp.net-web-api

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

但是我们很难理解代码片段通过C#调用它.我们知道我们必须请求一个请求令牌并将其附加到头部以便后续请求.我们尝试了DotNetOpenAuth和Owin,但无法找到实现此实际代码/到目前为止没有成功.任何人都可以通过一小段C#代码来帮助我实现这一目标吗?

jum*_*uro 10

要请求访问令牌,您只需要发送身份验证数据的请求.此代码已使用资源所有者密码凭据grant从工作的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;
}
Run Code Online (Sandbox Code Playgroud)

我希望它有所帮助.

编辑

这里有一个代码片段来刷新令牌:

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;
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 您必须附加相同的令牌,直到获得 401 - 未经授权的响应,然后您需要获取新的访问令牌,无论是发布资源所有者凭据还是使用刷新令牌(如果您的授权服务器实现此功能)。刷新令牌授予请求类似于凭证,但对用户是透明的,不需要重新输入他们的凭证。请查看带有新代码片段的编辑后的响应。 (2认同)
  • 如果在会话中保存令牌,则取决于会话的持久性。考虑到如果会话在令牌之前过期,您将需要在创建新会话时请求新令牌。 (2认同)