首页 > 解决方案 > 在 Identity Server ASP.NET Core 中获取 accessToken

问题描述

我将 IdentityServer 与 ASP.NET Core MVC 应用程序一起使用。

在 IdentityServer 我的客户端定义如下:

new Client
    {
        ClientId = "admin.client",
        ClientName = "Admin Application",
        AllowedGrantTypes = GrantTypes.Implicit,
        ClientSecrets =
                        {
                            new Secret("secret".Sha256())
                        },
        RedirectUris = { "http://localhost:45876/signin-oidc" },
        PostLogoutRedirectUris = { "http://localhost:45876/signout-callback-oidc" },
        AllowedCorsOrigins = new[] { "http://localhost:45876/" },
        AllowedScopes =
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            IdentityServerConstants.StandardScopes.Profile
                        },
        AllowOfflineAccess = true
}

客户注册如下:

services.AddAuthentication(
            options =>
                {
                    options.DefaultScheme = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
            .AddCookie("Cookies")
            .AddOpenIdConnect(
                "oidc",
                options =>
                    {
                        options.SignInScheme = "Cookies";

                        options.Authority = "http://localhost:5001/";
                        options.RequireHttpsMetadata = false;


                        options.ClientId = "admin.client";
                        options.ClientSecret = "secret";
                        options.ResponseType = "code id_token";
                        options.SaveTokens = true;
                        options.GetClaimsFromUserInfoEndpoint = true;

                        options.Scope.Add("openid");
                        options.Scope.Add("profile");
                    });

我的问题是当我想获取为空的 accessToken 时。

我正在尝试使用以下代码来获取它:

 var token = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");
 string accessToken = User.FindFirst("access_token")?.Value;

它们都返回null。

我的问题在哪里?

标签: c#asp.net-coreidentityserver4

解决方案


第一个问题是您正在配置客户端应用程序以使用Hybrid flow与 IdentityServer 交互:

 options.ResponseType = "code id_token";

但是客户端配置只允许使用Implicit flow

 AllowedGrantTypes = GrantTypes.Implicit,

这将invalid grant type在身份验证请求期间引发错误。

第二个问题是您没有配置ApiResource

public static IEnumerable<ApiResource> GetApis()
{
    return new List<ApiResource>
    {
        new ApiResource("api1", "My API")
    };
}

客户端也没有请求访问 api 资源的权限,虽然您可以让客户端应用程序使用身份服务器对用户进行身份验证,但它会返回ID token,而不是Access token

  • ID token至少包含用户的标识符(称为 sub aka 主题声明)以及有关用户如何以及何时进行身份验证的信息

  • Access token允许访问 API 资源,包含有关客户端和用户的信息(如果存在)。

由于您使用的是 Web 应用程序(mvc 作为客户端应用程序)。一个更好的使用选择hybrid flow,它支持 API 访问和用户身份验证。是代码示例。


推荐阅读