问题
I am developing an ASP .Net Core 1.1 MVC web app which calls a web API using the "Authorization Code Grant Flow". I am using Auth0 for the authentication server.
Following the Auth0 tutorials, at the point the user has successfully logged in to the web app, and now does something that makes the web app call upon the web api, it says I should get the access token as follows:
public async Task<IActionResult> Index()
{
string accessToken = User.Claims.FirstOrDefault("access_token")?.Value;
if (accessToken == "")
return View("Error");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage responseMessage = await client.GetAsync(inspectionsUrl);
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
List<Inspection> inspections = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Inspection>>(responseData);
return View(inspections);
}
return View("Error");
}
However, this doesn't even compile, giving the following
Argument 2: cannot convert from 'string' to 'System.Func <System.Security.Claims.Claim, bool>'
Any ideas?
回答1:
The first line should probably be:
string accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token")?.Value;
Right now you are trying to give "access_token"
as an argument to FirstOrDefault
, which won't work. You have to specify a predicate.
回答2:
You can write extension and use more elegant way for retrieving access token:
var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");
来源:https://stackoverflow.com/questions/44240080/retrieving-access-token-in-controller