在控制器中检索访问令牌 [英] Retrieving access token in controller

查看:37
本文介绍了在控制器中检索访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 ASP .Net Core 1.1 MVC Web 应用程序,它使用授权代码授予流程"调用 Web API.我使用 Auth0 作为身份验证服务器.

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.

按照 Auth0 教程,当用户成功登录到 Web 应用程序时,现在执行一些使 Web 应用程序调用 Web api 的操作,它说我应该按如下方式获取访问令牌:

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>'

有什么想法吗?

推荐答案

第一行应该是:

string accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token")?.Value;

现在您正试图将 "access_token" 作为参数提供给 FirstOrDefault,但这是行不通的.您必须指定一个谓词.

Right now you are trying to give "access_token" as an argument to FirstOrDefault, which won't work. You have to specify a predicate.

这篇关于在控制器中检索访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆