我开始用 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");
}
错误出现在我的 TwitterClient的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 Unauthorized 回复?DotNetOpenAuth 和 Twitter 是否存在已知问题?
非常感谢任何帮助。