如何使用Twitter对用户进行身份验证,但不能用于登录

时间:2016-08-25 02:17:50

标签: c# twitter oauth asp.net-mvc-5 linq-to-twitter

我安装了MVC5,经过一天我觉得是时候伸出援助之手了,我从未成为OAuth Guru,其他的事情是肯定的,但是没有。我搜索了互联网,但没有人专门关注身份验证过程而没有其他任何内容,或者讨论太松散,以至于我无法理解我试图学习的特定框架的逻辑概念。

我有一个MVC控制器,在我看来,当用户点击按钮进行身份验证时,这是一个名为Social的简单操作。所以我的网址是http://localhost://mywebsite/enterprise/social我知道这是学校男孩的东西,但我需要帮助,我从一开始就开始使用1.0 OAuth

我不想使用Twitter进行登录,它用于我多年前制作的自定义Twitter盒子,用于发推,重发推文,基本上就像在Twitter上一样。 不适合他们登录网站

我希望将其用于Twitter,他们登录,重定向回相同的MVC页面,我捕获令牌,保存到我的人员存储,并完成。

之后的所有电话我都会自己调用数据库并创建自己的cookie,以备将来调用,因为它已经创建,所以我将继续使用它,没有特殊目的。

所以,这是我的控制器,我哪里出错?

public async Task Social(FormCollection form)
{

    //var auth = new MvcSignInAuthorizer
    var auth = new MvcAuthorizer
    {
        CredentialStore = new InMemoryCredentialStore
        {
            ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
            ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]
        }
    };

    string twitterCallbackUrl = Request.Url.ToString().Replace("Begin", "Complete");
    auth.Callback = new Uri(twitterCallbackUrl);

    await auth.BeginAuthorizationAsync();
}
public async Task<PartialViewResult> CompleteAsync()
{
    var auth = new MvcAuthorizer
    {
        CredentialStore = new InMemoryCredentialStore()
    };

    await auth.CompleteAuthorizeAsync(HttpContext.Request.Url);

    var credentials = auth.CredentialStore;
    string oauthToken = credentials.OAuthToken,
           oauthTokenSecret = credentials.OAuthTokenSecret,
           screenName = credentials.ScreenName,
           userName = Membership.GetUser().UserName;
    ulong userID = credentials.UserID;


    System.Web.Profile.ProfileBase pro = System.Web.Profile.ProfileBase.Create(userName, true);
    pro.SetPropertyValue("twoauth_token", oauthToken);
    pro.SetPropertyValue("twtokensecret", oauthTokenSecret);
    pro.Save();

    HttpContext.Response.SetOauthFromCookie("twit", oauthTokenSecret, oauthToken, userName, true);

    ViewBag.IsTwitterConnected = IsTwitterConnected;
    return PartialView("_SocialPartial");
}

这是我的Startup.cs

    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);



            app.UseTwitterAuthentication(
                new TwitterAuthenticationOptions
                {
                    ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],
                    Provider = new LinqToTwitterAuthenticationProvider()
                });

        }
    }
}

重新安排代码以完成我需要它与MVC 5 4.6.2框架做的事情真棒!

1 个答案:

答案 0 :(得分:1)

我不确定你的意思是“我不想使用Twitter登录”。如果您指的是旧的用户名/密码凭据登录,则不推荐使用,无论如何都不能使用它。 System.Web.Profile...SetOAuthFromCookie...不是LINQ to Twitter的一部分 - 或许你所指的是登录代码?

听起来您想要实现正常的OAuth工作流程。在这种情况下,我使用OAuthController来隔离代码并简化我的调用代码,如下所示:

public class OAuthController : AsyncController
{
    public ActionResult Index()
    {
        return View();
    }

    public async Task<ActionResult> BeginAsync()
    {
        //var auth = new MvcSignInAuthorizer
        var auth = new MvcAuthorizer
        {
            CredentialStore = new SessionStateCredentialStore
            {
                ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"]
            }
        };

        string twitterCallbackUrl = Request.Url.ToString().Replace("Begin", "Complete");
        return await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl));
    }

    public async Task<ActionResult> CompleteAsync()
    {
        var auth = new MvcAuthorizer
        {
            CredentialStore = new SessionStateCredentialStore()
        };

        await auth.CompleteAuthorizeAsync(Request.Url);

        // This is how you access credentials after authorization.
        // The oauthToken and oauthTokenSecret do not expire.
        // You can use the userID to associate the credentials with the user.
        // You can save credentials any way you want - database, 
        //   isolated storage, etc. - it's up to you.
        // You can retrieve and load all 4 credentials on subsequent 
        //   queries to avoid the need to re-authorize.
        // When you've loaded all 4 credentials, LINQ to Twitter will let 
        //   you make queries without re-authorizing.
        //
        //var credentials = auth.CredentialStore;
        //string oauthToken = credentials.OAuthToken;
        //string oauthTokenSecret = credentials.OAuthTokenSecret;
        //string screenName = credentials.ScreenName;
        //ulong userID = credentials.UserID;
        //

        return RedirectToAction("Index", "Home");
    }
}

请注意CredentialStoreSessionStateCredentialStore,它会将您的令牌保持在会话状态。如果您不喜欢保存凭据的方式,请实现您自己的ICredentialStore - 它可以像这样扩展。另外,查看CompleteAsync中的注释 - 它们会向您展示如何提取所有凭据以在数据库中保留(或者如果您愿意,还可以在cookie中使用特定于用户的标记)。

由于凭据在授权后处于会话状态,因此需要运行LINQ到Twitter的任何代码都可以检查这些凭据是否可用,如下所示:

        if (!new SessionStateCredentialStore().HasAllCredentials()) 
            return RedirectToAction("Index", "OAuth"); 

使用LINQ to Twitter,如果授权者拥有全部4个凭据,您可以实例化TwitterContext并执行您需要的操作。 HasAllCredentials()告诉您是否所有4个凭据都可用。如果没有,请再次启动OAuth流程。此演示将用户带到一个页面以手动启动授权过程,但您可以直接重定向到BeginAsync

在实际代码中,另一项改进是修改BeginAsync,以便从数据库(或其他商店,例如cookie)查找用户的凭据,填充SessionStateCredentialStore,并重定向回到来电者。如果用户凭据不可用,则让用户完成OAuth流程,然后保存凭据,以便您不必再次执行此操作。

如果您想查看整个演示,请访问LINQ to Twitter Samples文件夹中的MVCDemo project

如果您收到以下错误,则应在Twitter应用程序设置中填写“回拨网址”。这是一个Q / A,其中有人有同样的问题:

Desktop applications only support the oauth_callback value 'oob'/oauth/request_token

Receiving Server Error



Server Error in '/' Application.
<?xml version="1.0" encoding="UTF-8"?>
<hash>
 <error>Desktop applications only support the oauth_callback value 'oob'</error>
 <request>/oauth/request_token</request>
</hash>
- Please visit the LINQ to Twitter FAQ (at the HelpLink) for help on resolving this error.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: LinqToTwitter.TwitterQueryException: <?xml version="1.0" encoding="UTF-8"?>
<hash>
 <error>Desktop applications only support the oauth_callback value 'oob'</error>
 <request>/oauth/request_token</request>
</hash>
- Please visit the LINQ to Twitter FAQ (at the HelpLink) for help on resolving this error.

Source Error:


Line 55:         protected async void AuthorizeButton_Click(object sender, EventArgs e)
Line 56:         {
Line 57:             await auth.BeginAuthorizeAsync(Request.Url);
Line 58:         }
Line 59:     }


Source File: D:\Users\Errrrrrr\Documents\visual studio 2015\ForTesting\LinqToTwitter-master\Samples\net46\CSharp\AspNetSamples\WebFormsDemo\OAuth.aspx.cs    Line: 57

Stack Trace:


[TwitterQueryException: <?xml version="1.0" encoding="UTF-8"?>
<hash>
  <error>Desktop applications only support the oauth_callback value 'oob'</error>
  <request>/oauth/request_token</request>
</hash>
 - Please visit the LINQ to Twitter FAQ (at the HelpLink) for help on resolving this error.]
   LinqToTwitter.Net.<HandleUnauthorizedAsync>d__4.MoveNext() +494
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +14139120
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   LinqToTwitter.Net.<ThrowIfErrorAsync>d__0.MoveNext() +360
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +14139120
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   LinqToTwitter.<HttpGetAsync>d__57.MoveNext() +1159
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +14139120
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   LinqToTwitter.<GetRequestTokenAsync>d__50.MoveNext() +675
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +14139120
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   LinqToTwitter.<BeginAuthorizeAsync>d__14.MoveNext() +568
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +14139120
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +28
   WebFormsDemos.<AuthorizeButton_Click>d__2.MoveNext() in D:\Users\Edddddd\Documents\visual studio 2015\ForTesting\LinqToTwitter-master\Samples\net46\CSharp\AspNetSamples\WebFormsDemo\OAuth.aspx.cs:57
   System.Runtime.CompilerServices.<>c.<ThrowAsync>b__6_0(Object state) +56
   System.Web.Util.SynchronizationHelper.SafeWrapCallback(Action action) +110
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +14139120
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
   System.Web.Util.WithinCancellableCallbackTaskAwaiter.GetResult() +32
   System.Web.UI.<ProcessRequestMainAsync>d__523.MoveNext() +7762