c# - 在 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。
我的问题在哪里?
解决方案
第一个问题是您正在配置客户端应用程序以使用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 访问和用户身份验证。这是代码示例。
推荐阅读
- angular - Angular:获取父路由中的参数值
- mysql - 如何使用 group_concat 和 concat 引用单列的值,不同
- javascript - 是否可以将参数名称作为字符串形式的参数传递以用作函数中的参数名称?
- python - 根据另一列中的字符串内容在 pandas 中创建类别列
- post - “此路线不支持 POST 方法。支持的方法:GET、HEAD
- swift - “navigationController?.pushViewController”和“performSegue”之间有什么区别吗
- php - Laravel 5.5 中 m:m 雄辩关系的 1:1 变体:示例有效吗?
- django - Django-Rest-Framework 无法解析超链接关系的 URL
- java - 我应该如何将我的 Java 代码转换为 J-meter BeanShell PreProcessor
- javascript - `Hooks` 是否可以用来替代 React 中的 `Redux`?