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

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

问题描述

我正在开发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天全站免登陆