无法将PLAINTEXT签名与DotNetOpenAuth ServiceProvider一起使用


69

我正在OAuth 1.0(a)使用DotNetOpenAuth(NuGet package DotNetOpenAuth.OAuth.ServiceProvider, version = 4.1.4.12333)构建授权服务器。该服务器托管在ASP.NET应用程序中,但这与问题无关。

ServiceProvider的配置如下:

private ServiceProvider GetServiceProvider()
{
    var baseUri = "http://myauth.com";
    return new ServiceProvider(
        new ServiceProviderDescription
        {
            UserAuthorizationEndpoint = new MessageReceivingEndpoint(
                new Uri(baseUri + "/get_request_token"), 
                HttpDeliveryMethods.GetRequest
            ),
            RequestTokenEndpoint = new MessageReceivingEndpoint(
                new Uri(baseUri + "/authorize"), 
                HttpDeliveryMethods.PostRequest
            ),
            AccessTokenEndpoint = new MessageReceivingEndpoint(
                new Uri(baseUri + "/get_token"), 
                HttpDeliveryMethods.PostRequest
            ),
            ProtocolVersion = ProtocolVersion.V10a,
            TamperProtectionElements = new ITamperProtectionChannelBindingElement[] 
            {
                new PlaintextSigningBindingElement(),
                new HmacSha1SigningBindingElement(),
            },
        },
        tokenManager,
        new OAuthServiceProviderMessageFactory(tokenManager)
    );
}

get_request_token端点的相关部分如下所示:

var serviceProvider = GetServiceProvider();
var tokenRequest = serviceProvider.ReadTokenRequest();

现在,当使用者将以下请求发送到此端点时:

GET /get_request_token?oauth_nonce=C5657420BCE5F3224914304376B5334696B09B7FFC17C105A7F9629A008869DC&oauth_timestamp=1356006599&oauth_consumer_key=sampleconsumer&oauth_signature_method=plaintext&oauth_signature=samplesecret%26&oauth_version=1.0&oauth_callback=http%3a%2f%2flocalhost%3a30103%2fCustomOAuth1 HTTP/1.1

Host: localhost:8180
Connection: close

(为清楚起见而中断):

oauth_nonce=C5657420BCE5F3224914304376B5334696B09B7FFC17C105A7F9629A008869DC
oauth_timestamp=1356006599
oauth_consumer_key=sampleconsumer
oauth_signature_method=plaintext
oauth_signature=samplesecret%26
oauth_version=1.0
oauth_callback=http%3a%2f%2flocalhost%3a30103%2fCustomOAuth1

serviceProvider.ReadTokenRequest()方法引发异常:

The UnauthorizedTokenRequest message required protections {All} but the channel could only apply {Expiration, ReplayProtection}.
   at DotNetOpenAuth.Messaging.Channel.ProcessIncomingMessage(IProtocolMessage message)
   at DotNetOpenAuth.Messaging.Channel.ReadFromRequest(HttpRequestBase httpRequest)
   at DotNetOpenAuth.Messaging.Channel.TryReadFromRequest[TRequest](HttpRequestBase httpRequest, TRequest& request)
   at DotNetOpenAuth.OAuth.ServiceProvider.ReadTokenRequest(HttpRequestBase request)
   at DotNetOpenAuth.OAuth.ServiceProvider.ReadTokenRequest()
   at OAuthServers.OAuth1.Services.OAuth1Service.Any(GetRequestTokenRequest request)
   at lambda_method(Closure , Object , Object )
   at ServiceStack.ServiceHost.ServiceRunner`1.Execute(IRequestContext requestContext, Object instance, TRequest request)

另一方面,如果客户端发送以下请求:

GET /get_request_token?oauth_callback=http%3a%2f%2flocalhost%3a65271%2foauth1%2fHandleAccessToken&oauth_consumer_key=sampleconsumer&oauth_nonce=rGFvxlWm&oauth_signature_method=HMAC-SHA1&oauth_signature=HV%2f5Vq%2b0cF3NrtiISE9k4jmgCrY%3d&oauth_version=1.0&oauth_timestamp=1356007830 HTTP/1.1

Host: localhost:8180
Connection: close

(为清楚起见而中断):

oauth_callback=http%3a%2f%2flocalhost%3a65271%2foauth1%2fHandleAccessToken
oauth_consumer_key=sampleconsumer
oauth_nonce=rGFvxlWm
oauth_signature_method=HMAC-SHA1
oauth_signature=HV%2f5Vq%2b0cF3NrtiISE9k4jmgCrY%3d
oauth_version=1.0
oauth_timestamp=1356007830

成功了。

如您所见,这两个请求之间的唯一区别是oauth_signature_method正在使用。在第一种情况下PLAINTEXT使用,而在第二种情况下HMAC-SHA1

是否可以使DotNetOpenAuthPLAINTEXT与GET动词一起接受请求令牌端点的签名方法(即使OAuth 1.0(a) specification推荐将POST用于该端点)?是否有一些配置选项可以缓解服务器上的这一要求?

目前,修改客户端不是我的选择。


您正在使用SSL吗?纯文本需要HTTPS URL。
Andrew Arnott

不,我没有将SSL用于测试站点。我已经relaxSslRequirements="true"<messaging>元素的web.config中进行了设置。让我尝试激活SSL,看看是否可行。
Darin Dimitrov

在服务器上激活SSL不能解决问题。值得一提的是,我在服务器(IIS Express)上使用了无效的SSL证书,并使用忽略了来自客户端的SSL错误,ServicePointManager.ServerCertificateValidationCallback但这通常不应该影响服务器,对吗?无论如何,我最终都会修改客户端以使用HMAC-SHA1,但是只是想知道是否可以在不修改客户端的情况下解决该问题(出于个人利益,并且更好地了解DotNetOpenAuth的工作原理)。
Darin Dimitrov

我的另一个想法是,您的服务器端代码添加了两个签名绑定元素(纯文本和hmac-sha1)。您可以尝试仅显示纯文本元素,看看是否可以使客户端正常工作吗?
安德鲁·阿诺特

我已经尝试过仅使用纯文本签名元素以及仅使用hmac-sha1。他们俩都没有工作。
Darin Dimitrov

Answers:


1

OAuth身份验证通过三个步骤完成:

  1. 消费者获得未授权的请求令牌。

  2. 用户授权请求令牌。

  3. 消费者将请求令牌交换为访问令牌。

因此,结果如下所示:

public class InMemoryTokenManager : IConsumerTokenManager, IOpenIdOAuthTokenManager
{
private Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>();

public InMemoryTokenManager(string consumerKey, string consumerSecret)
{
    if (String.IsNullOrEmpty(consumerKey))
    {
        throw new ArgumentNullException("consumerKey");
    }

    this.ConsumerKey = consumerKey;
    this.ConsumerSecret = consumerSecret;
}

public string ConsumerKey { get; private set; }

public string ConsumerSecret { get; private set; }

#region ITokenManager Members

public string GetConsumerSecret(string consumerKey)
{
    if (consumerKey == this.ConsumerKey)
    {
        return this.ConsumerSecret;
    }
    else
    {
        throw new ArgumentException("Unrecognized consumer key.", "consumerKey");
    }
}

public string GetTokenSecret(string token)
{
    return this.tokensAndSecrets[token];
}

public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response)
{
    this.tokensAndSecrets[response.Token] = response.TokenSecret;
}

public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret)
{
    this.tokensAndSecrets.Remove(requestToken);
    this.tokensAndSecrets[accessToken] = accessTokenSecret;
}

/// <summary>
/// Classifies a token as a request token or an access token.
/// </summary>
/// <param name="token">The token to classify.</param>
/// <returns>Request or Access token, or invalid if the token is not recognized.</returns>
public TokenType GetTokenType(string token)
{
    throw new NotImplementedException();
}

#endregion

#region IOpenIdOAuthTokenManager Members

public void StoreOpenIdAuthorizedRequestToken(string consumerKey, AuthorizationApprovedResponse authorization)
{
    this.tokensAndSecrets[authorization.RequestToken] = string.Empty;
}

#endregion
}

1

以下代码块可以帮助您生成纯文本签名

public static string GetSignature(OAuthSignatureMethod signatureMethod,             AuthSignatureTreatment signatureTreatment, string signatureBase, string consumerSecret, string tokenSecret)
{
    if (tokenSecret.IsNullOrBlank())
    {
        tokenSecret = String.Empty;
    }

    consumerSecret = UrlEncodeRelaxed(consumerSecret);
    tokenSecret = UrlEncodeRelaxed(tokenSecret);

    string signature;
    switch (signatureMethod)
    {
        case OAuthSignatureMethod.HmacSha1:
        {
            var crypto = new HMACSHA1();
            var key = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

            crypto.Key = _encoding.GetBytes(key);
            signature = signatureBase.HashWith(crypto);

            break;
        }
        case OAuthSignatureMethod.PlainText:
        {
            signature = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

            break;
        }
        default:
            throw new NotImplementedException("Only HMAC-SHA1 is currently supported.");
        }

        var result = signatureTreatment == OAuthSignatureTreatment.Escaped
            ? UrlEncodeRelaxed(signature)
            : signature;

        return result;
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.