我有访问令牌和oauth_verifier,但我也需要从Twitter获取acess_secret. https://dev.twitter.com/docs/auth/implementing-sign-twitter
我缺少的是如何将oauth_verifier传递回Twitter以使用OAuthWebSecurity获取访问密码.
再次,我可以使用Twitter登录确定,但我需要能够使用Twitter作为用户.我之前使用TweetSharp库完成了这项工作,但我正在尝试在此项目中使用DotNetOpenAuth.
更新:
我正在使用第一个链接中描述的OAuthWebSecurity类来管理身份验证. AuthConfig中的OAuthWebSecurity.RegisterClient需要DotNetOpenAuth.AspNet.IAuthenticationClient.您无法按照建议将其与TwitterConsumer类交换出来.
我可以使用第一个链接中描述的“内置”DotNetOpenAuth身份验证部分,或者我可以使用自定义代码进行完全授权,但我正在尝试找到两种方法.
我可以单独执行此操作,但随后会向用户显示两次Twitter对话框(一次登录,一次授权).我希望有一种方法可以使用已经连线的认证文件,它使用OAuthWebSecurity,但也可以使用授权文件.
解决方法
首先,创建一个新的OAuthClient:
public class TwitterClient : OAuthClient { /// <summary> /// The description of Twitter's OAuth protocol URIs for use with their "Sign in with Twitter" feature. /// </summary> public static readonly ServiceProviderDescription TwitterServiceDescription = new ServiceProviderDescription { RequestTokenEndpoint = new MessageReceivingEndpoint( "https://api.twitter.com/oauth/request_token",HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),UserAuthorizationEndpoint = new MessageReceivingEndpoint( "https://api.twitter.com/oauth/authenticate",AccessTokenEndpoint = new MessageReceivingEndpoint( "https://api.twitter.com/oauth/access_token",TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },}; public TwitterClient(string consumerKey,string consumerSecret) : base("twitter",TwitterServiceDescription,consumerKey,consumerSecret) { } /// Check if authentication succeeded after user is redirected back from the service provider. /// The response token returned from service provider authentication result. protected override AuthenticationResult VerifyAuthenticationCore(AuthorizedTokenResponse response) { string accessToken = response.AccessToken; string accessSecret = (response as ITokenSecretContainingMessage).TokenSecret; string userId = response.ExtraData["user_id"]; string userName = response.ExtraData["screen_name"]; var extraData = new Dictionary<string,string>() { {"accesstoken",accessToken},{"accesssecret",accessSecret} }; return new AuthenticationResult( isSuccessful: true,provider: ProviderName,providerUserId: userId,userName: userName,extraData: extraData); } }
重要的部分是将响应强制转换为ITokenSecretContainingMessage.似乎响应始终具有TokenSecret,但它仅在内部属性上.通过投射,您可以访问公共财产.我不能说我喜欢这样做,但后来我也不明白为什么DotNetOpenAuth Asp.Net团队首先隐藏了这个属性.一定有充分的理由.
然后在AuthConfig中注册此客户端:
OAuthWebSecurity.RegisterClient( new TwitterClient( consumerKey: "",consumerSecret: ""),"Twitter",null);
现在,在AccountController上的ExternalLoginCallback方法中,accessSecret在ExtraData字典中可用.