William Leme

Software Engineer

Accessing OAuth access token in Asp.Net Core 2

Posted at — Jan 29, 2019

You can easily access the OAuth access token by calling

GetTokenAsync.

Make sure to set SaveTokens = true when setting up OAuth middleware

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public void ConfigureServices(IServiceCollection services)
{
	services.AddAuthentication(options =>
	{
		options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
		options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
		options.DefaultChallengeScheme = "CustomName";
	})
	.AddCookie(options =>
	{
		options.Cookie.Name = "CustomName";
	})
	.AddOAuth("CustomName", options =>
	{
		//set all options...

		options.SaveTokens = true;
	});
}

Access token

You can then access the token by calling GetTokenAsync in your controller

var token = await HttpContext.GetTokenAsync("access_token");