Auth0 Home Blog Docs

How to get token well retrieved in services into controller (Core 2.0 oAuth 2) ?

token
aspnet-core
linkedin
oauth2
controller

#1

In ASP.Net MVC Core 2, we are trying to call the Linkedin web API with OAuth authentication.
We are able to declare the OAuth authentication service and retrieve the access token from Linkedin as shown in the code below.
Now we would like to request the API from a controller. To do that, we have to get the access token from the OAuth service we have declared with the AddOAuth method. How can we do that? No way to find an example anywhere.

Thanx for your help, we are really stuck.

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
           .AddCookie("linkedin_login", options =>
           {
               options.LoginPath = new PathString("/login");
               options.LogoutPath = new PathString("/logout");
           })
           .AddOAuth("LinkedIn", options =>
           {
               options.SignInScheme = "linkedin_login";
               options.ClientId = Configuration"linkedin:clientId"];
               options.ClientSecret = Configuration"linkedin:clientSecret"];
               options.CallbackPath = new PathString("/signin-linkedin");

               options.AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization";
               options.TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken";
               options.UserInformationEndpoint = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,formatted-name,email-address,picture-url,picture-urls,headline,public-profile-url,industry,three-current-positions,three-past-positions,positions::(original))";
              
               // To save the tokens to the Authentication Properties we need to set this to true
               // See code in OnTicketReceived event below to extract the tokens and save them as Claims
               options.SaveTokens = true;

               options.Scope.Add("r_basicprofile");
               options.Scope.Add("r_emailaddress");

               options.Events = new OAuthEvents
               {
                   OnCreatingTicket = async context =>
                   {
                       #region OnCreatingTicket
                       // Retrieve user info
                       var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                       request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                       request.Headers.Add("x-li-format", "json"); // Tell LinkedIn we want the result in JSON, otherwise it will return XML

#2

Have you tried using:
var token = await HttpContext.GetTokenAsync(“access_token”);


#3