在控制器中检索访问令牌

时间:2017-05-29 10:19:39

标签: authorization asp.net-core-mvc access-token auth0

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

在Auth0教程之后,用户已成功登录到Web应用程序,现在做了一些使Web应用程序调用web api的内容,它说我应该获取访问令牌,如下所示:

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");
}

然而,这甚至没有编译,给出以下

Argument 2: cannot convert from 'string' to 'System.Func <System.Security.Claims.Claim, bool>'

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

第一行应该是:

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

现在,您正尝试将"access_token"作为FirstOrDefault的参数,而LOCAL_PATH := $(call my-dir) OPENCV_PATH := D:/CODE/OpenCV-2.4.10-android-sdk/sdk/native/jni include $(CLEAR_VARS) LOCAL_MODULE := nonfree LOCAL_SRC_FILES := libnonfree.so include $(PREBUILT_SHARED_LIBRARY) include $(CLEAR_VARS) #opencv OPENCVROOT:= C:\OpenCV-2.4.10-android-sdk OPENCV_CAMERA_MODULES:=on OPENCV_INSTALL_MODULES:=on OPENCV_LIB_TYPE:=SHARED include ${OPENCVROOT}/sdk/native/jni/OpenCV.mk LOCAL_SRC_FILES := com_example_adrien_ndkopencvtest4_OpencvNativeClass.cpp LOCAL_SHARED_LIBRARIES += nonfree LOCAL_LDLIBS += -llog LOCAL_MODULE := MyOpencvLibs include $(BUILD_SHARED_LIBRARY) 无法正常工作。您必须指定谓词。

答案 1 :(得分:1)

您可以编写扩展名并使用更优雅的方式来检索访问令牌:

var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");