65.9K
CodeProject 正在变化。 阅读更多。
Home

.NET (C#) 中的双腿 OAuth 身份验证

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (8投票s)

2012 年 7 月 5 日

CPOL

1分钟阅读

viewsIcon

99273

downloadIcon

3419

.NET (C#) 中的双腿 OAuth 身份验证

引言

OAuth 是一种开放的授权标准。它允许应用程序在未经用户分享密码的情况下,代表用户行事。 在本文中,我将详细介绍如何使用 OAuth.net 库在 C# 中执行双腿 OAuth 身份验证。 您可以在以下网址阅读完整的 OAuth 规范:https://oauth.ac.cn/

您可以在 Java 中找到很多示例和示例代码。 但我没有找到一个足够好的 .NET 示例。 在我的一次任务中,我不得不花费大量时间来执行此操作,所以我决定写这篇文章。

背景

OAuth 提供了两种身份验证方式:三腿或双腿身份验证。

双腿身份验证意味着客户已经拥有有效的 OAuth 消费者凭据(密钥和密钥)。 您需要根据 OAuth 消费者请求规范对请求进行签名,以创建用户的 OAuth 令牌请求。 以下 OAuth 文章提供了关于执行 OAuth 消费者请求所需的所有内容的非常详细的说明。

https://oauth.ac.cn/core/1.0/#sig_base_example

双腿身份验证的主要优点是用户体验无缝,因为无需额外的用户交互即可启动 API 会话。

使用代码

代码不言自明。 使用附带的 ServiceProvider 类来实例化 OAuth 请求。 您可以使用 PostData\GetData 方法分别执行 POST\GET 请求。

ServiceProvider provider = new ServiceProvider(serviceUrl, consumerKey, secret);
//Perform a POST requestString response = provider.PostData("application/json", data);

The GenerateRequest function shows how to sign an OAuth Request.   

private HttpWebRequest GenerateRequest(string contentType, string requestMethod)
{
    var ts = UnixTime.ToUnixTime(DateTime.Now);
    //Create the needed OAuth Parameters.
    //Refer - https://oauth.ac.cn/core/1.0/#sig_base_example
    var param = new OAuthParameters() {
    ConsumerKey = _consumerKey,
        SignatureMethod = SigningProvider.SignatureMethod,
        Version = Constants.Version1_0,
        Nonce = NonceProvider.GenerateNonce(ts),
        Timestamp = ts.ToString(),
    };
    //Generate Signature Hash
    var signatureBase = SignatureBase.Create(requestMethod.ToUpper(), _serviceProviderUri, param);
    //Set Signature Hash as one of the OAuth Parameter
    param.Signature = SigningProvider.ComputeSignature(signatureBase, _consumerSecret, null);
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(_serviceProviderUri);
    httpWebRequest.Method = requestMethod;
    httpWebRequest.ContentType = contentType;
    httpWebRequest.Timeout = RequestTimeOut;
    //Add the OAuth Parameters to Authorization Header of Request
    httpWebRequest.Headers.Add(Constants.AuthorizationHeaderParameter, param.ToHeaderFormat());
    return httpWebRequest;
}

依赖项

该代码依赖于 OAuth.Net 库 (http://code.google.com/p/oauth-dot-net/)。 您需要添加对 OAuth 库的引用才能编译代码。

© . All rights reserved.