Search code examples
c#asp.net-mvcasp.net-mvc-5linq-to-twitter

LinqToTwitter user authorization ASP.NET MVC


i am using LinqToTwitter in my asp.net MVC we application and i have the following problem. MY method for signing in using twitter looks like this:

    [Authorize(Roles = UserRoleNames.EmployeeOrManager)]
    public virtual async Task<ActionResult> LoginToTwitter(int campaignId)
    {            
        string twitterCallbackUrl = Url.SecureActionAbsolute(MVC.Campaign.TwitterAccessToken(campaignId));
        return await TwitterApi.Current.BeginAuthorization(twitterCallbackUrl);
    }

    public async Task<ActionResult> BeginAuthorization(string twitterCallbackUrl)
    {
        var auth = new LinqToTwitter.MvcAuthorizer
        {
            CredentialStore = new LinqToTwitter.SessionStateCredentialStore
            {
                ConsumerKey = ConfigurationManager.AppSettings["TwitterAppKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["TwitterAppSecret"]
            }
        };


        return await auth.BeginAuthorizationAsync(new Uri(twitterCallbackUrl));
    }

The problem i have is that when i first authorize using this code everything works fine - i go to my callback method and store the access token and access token secret of authorized user, but when i try to do it for the second time (while logged out of the twitter) i am not getting redirected to my callback. The hing is that my application user is connected with multiple twitter accounts, so i need to retrieve multiple access tokens.


Solution

  • The SessionStateCredentialStore saves all the user's tokens in Session state. So, on subsequent authorizations those tokens still exist and the authorizer doesn't require the user to re-authorize your application. If you hit a breakpoint on the call to BeginAuthorizationAsync and inspect auth.CredentialStore, you'll see the populated values for OAuthToken and OAuthTokenSecret. you can let the user switch their Twitter user and re-authorize your application by clearing those values, like this:

    auth.CredentialStore.OAuthToken = null;
    auth.CredentialStore.OAuthTokenSecret = null;