我正为在Twitter上登录用户而感到烦恼!!!我的Facebook、Google和OpenId都能正常工作,只有Twitter让我十分头痛。
每次尝试运行我的代码时,我一直收到401 Unauthorized的提示,但就是无法找出原因所在。
我创建了一个Twitter客户端,并使用DotNetOpenAuth样例解决方案中的InMemoryTokenManager进行管理。我的Twitter客户端在这里。
public class TwitterClient
{
private string UserName { get; set; }
private static readonly ServiceProviderDescription ServiceDescription =
new ServiceProviderDescription
{
RequestTokenEndpoint = new MessageReceivingEndpoint(
"https://api.twitter.com/oauth/request_token",
HttpDeliveryMethods.GetRequest |
HttpDeliveryMethods.AuthorizationHeaderRequest),
UserAuthorizationEndpoint = new MessageReceivingEndpoint(
"https://api.twitter.com/oauth/authorize",
HttpDeliveryMethods.GetRequest |
HttpDeliveryMethods.AuthorizationHeaderRequest),
AccessTokenEndpoint = new MessageReceivingEndpoint(
"https://api.twitter.com/oauth/access_token",
HttpDeliveryMethods.GetRequest |
HttpDeliveryMethods.AuthorizationHeaderRequest),
TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
};
IConsumerTokenManager _tokenManager;
public TwitterClient(IConsumerTokenManager tokenManager)
{
_tokenManager = tokenManager;
}
public void StartAuthentication()
{
var request = HttpContext.Current.Request;
using (var twitter = new WebConsumer(ServiceDescription, _tokenManager))
{
var callBackUrl = new Uri(request.Url.Scheme + "://" + request.Url.Authority + "/Members/TwitterCallback");
twitter.Channel.Send(
twitter.PrepareRequestUserAuthorization(callBackUrl, null, null)
);
}
}
public bool FinishAuthentication()
{
using (var twitter = new WebConsumer(ServiceDescription, _tokenManager))
{
var accessTokenResponse = twitter.ProcessUserAuthorization();
if (accessTokenResponse != null)
{
UserName = accessTokenResponse.ExtraData["screen_name"];
return true;
}
}
return false;
}
}
我在MembersController的构造函数中有以下内容,它使用正确的凭据实例化了InMemoryTokenManager
_tokenManager = new InMemoryTokenManager(ConfigUtils.GetAppSetting("TwitterAppId"), ConfigUtils.GetAppSetting("TwitterAppSecret"));
我的两个行为是:
public ActionResult LogonTwitter()
{
var client = new TwitterClient(_tokenManager);
client.StartAuthentication();
return null;
}
public ActionResult TwitterCallback()
{
var client = new TwitterClient(_tokenManager);
if (client.FinishAuthentication())
{
return new RedirectResult("/");
}
// show error
return View("LogOn");
}
错误出现在我的Twitter客户端的StartAuthentication()函数中。一旦调用此行:
twitter.Channel.Send(
twitter.PrepareRequestUserAuthorization(callBackUrl, null, null)
);
我收到以下错误信息:
Error occurred while sending a direct message or getting the response.
Inner Exception: The remote server returned an error: (401) Unauthorized.
有人有什么建议吗?我已经花了大部分昨天和今天早上来解决这个问题。我尝试了所有的在线示例,但好像都会收到401未授权的错误?DotNetOpenAuth 和 Twitter 之间是否存在已知问题?
非常感谢任何帮助。