Retrieving access token in controller

僤鯓⒐⒋嵵緔 提交于 2020-01-15 08:04:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!