AspNetCore - Get current access token

Published on Thursday, July 14, 2016

Recently I was doing some fiddling with Fitbit authentication using the AspNet Security OAuth Providers to see if I could authenticate a website user with a Fitbit OAuth token and then use that access key to display some statistics on the amount of steps they have in a given work week.

The authentication component was relatively easy, just adding the dependency to the Fitbit security provider from NuGet and it worked. However, normally in the OWIN providers the code would add the Access Token to the current set of Claims in the ClaimsIdenitity object. In AspNetCore that was not the case.

app.UseFitbitAuthentication(options =>
    options.ClientId = "";
    options.ClientSecret = "";
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.SaveTokens = true;

So long story short, this is a basic HttpContext extension method to retrieve the Access Token from the AuthenticationManager

public static string GetFitbitUserAccessToken(this HttpContext context)
    var authInfo = context.Authentication.GetAuthenticateInfoAsync("Fitbit").Result;
    var tokens = authInfo.Properties.GetTokens();
    var accessToken = tokens.FirstOrDefault(t => t.Name == "access_token");

    return accessToken.Value;

Error handling removed for length

The key component here is the GetAuthenticateInfoAsync call. In a security configuration there could be multiple Auth "Schemes" you need to specify the one you are retrieving, some basic debugging will allow you to find the right one.

Hope this helps.

Thanks for reading.