S.Richmond
S.Richmond

Reputation: 11558

How do you retrieve a users' access token and secret in ASP.NET 5 Identity?

I'm developing a small app that allows a user to login to the site with their Twitter account. Then, once that is done, I intend to use the account to perform various actions with the Twitter API. However in order to do this I require the previously obtained access token and secret, but I don't know how.

I'm using .NET Core ASP.NET v5 on the boilerplate WebApp. Twitter authentication setup with:

app.UseTwitterAuthentication(new TwitterOptions()
{
    ConsumerKey     = "BLAH",
    ConsumerSecret  = "BLAH"
});

How do I retrieve the stored access token and secret once a user has successfully logged in with the Twitter auth?

I assume it is something along the lines of User.Identity.* or User.Claims.*.

Upvotes: 0

Views: 1484

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

You just need to add the values to the user's claims on authentication. In your Startup.Auth.cs, you'll need to add the following:

var twitterOptions = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions
{
    ConsumerKey = /* Your App's Consumer Key */,
    ConsumerSecret = /* Your App's Consumer Secret */,
    Provider = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationProvider
    {
        OnAuthenticated = (context) =>
        {
            context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_token", context.AccessToken, XmlSchemaString, "Twitter"));
            context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_token_secret", context.AccessTokenSecret, XmlSchemaString, "Twitter"));
            return Task.FromResult(0);
        }
    }
};
app.UseTwitterAuthentication(twitterOptions);

Then, when you need the values, you can retrieve them via:

var twitterTokenClaim = user.Claims.FirstOrDefault(m => m.ClaimType.EndsWith("twitter:access_token"));
var twitterSecretClaim = user.Claims.FirstOrDefault(m => m.ClaimType.EndsWith("twitter:access_token_secret"));

These are actual IdentityClaim instances, though, so you'll need to properly null-check and then access their ClaimValue property:

if (twitterTokenClaim != null && twitterSecretClaim != null)
{
    // work with Twitter API
    // Token and secret string values accessed via `twitterTokenClaim.ClaimValue`
    // and `twitterSecretClaim.ClaimValue`, respectively
}

Upvotes: 1

Related Questions