在MVC4中使用DotNetOpenAuth获取Twitter访问密钥

Mik*_*h99 3 dotnetopenauth twitter-oauth asp.net-mvc-4

我正在使用MVC4创建一个应用程序,该应用程序将使用Twitter授权用户,并允许他们从应用程序发送推文.我可以使用MVC4中的BuiltInOAuthClient.Twitter在没有问题的情况下对用户进行身份验证.http://www.asp.net/web-pages/tutorials/security/enabling-login-from-external-sites-in-an-aspnet-web-pages-site

我有访问令牌和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,但也可以使用授权文件.

Pau*_*tti 10

我已经用头撞了一下墙几天了,但我终于有了一些有用的东西.有兴趣知道它是否是一个有效的解决方案!

首先,创建一个新的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",
                HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
        AccessTokenEndpoint =
            new MessageReceivingEndpoint(
                "https://api.twitter.com/oauth/access_token",
                HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
        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);
    }
}
Run Code Online (Sandbox Code Playgroud)

重要的部分是将响应强制转换为ITokenSecretContainingMessage.似乎响应始终具有TokenSecret,但它仅在内部属性上.通过投射,您可以访问公共财产.我不能说我喜欢这样做,但后来我也不明白为什么DotNetOpenAuth Asp.Net团队首先隐藏了这个属性.一定有充分的理由.

然后在AuthConfig中注册此客户端:

OAuthWebSecurity.RegisterClient( new TwitterClient(
    consumerKey: "",
    consumerSecret: ""), "Twitter", null);
Run Code Online (Sandbox Code Playgroud)

现在,在AccountController上的ExternalLoginCallback方法中,accessSecret在ExtraData字典中可用.

  • 这样做得很好.我赞成.:)它是"隐藏的",因为设计是访问令牌秘密被塞进客户端提供的令牌管理器中.但是,您从此处派生的OAuthClient来自ASP.NET团队,他们试图简化体验并将令牌管理器隐藏起来.你的解决方案很好.在DNOA的未来版本中,获取此信息将更容易. (2认同)