C# 将web项目(ASP.NET Core 3)设置为IdentityServer的客户端和ApiResource
我知道这是荒谬的,而且做起来非常愚蠢,但是如果您想成为面向IdentityServer的C# 将web项目(ASP.NET Core 3)设置为IdentityServer的客户端和ApiResource,c#,authentication,asp.net-core,identityserver4,openid-connect,C#,Authentication,Asp.net Core,Identityserver4,Openid Connect,我知道这是荒谬的,而且做起来非常愚蠢,但是如果您想成为面向IdentityServer的客户机,以及使用引用令牌的ApiResource,您的Startup.cs(用于client+Api资源项目)必须是什么样子 我的想法如下:要求用户使用OpenID Connect进行身份验证。将凭据存储在cookie中,但之后不再依赖凭据,而是继续执行普通ApiResource使用引用令牌所做的操作->点击内省端点,检查令牌(从cookie中获取)是否有效,如果有效->允许访问,如果不可用->恢复到身份验证
客户机
,以及使用引用令牌的ApiResource
,您的Startup.cs(用于client+Api资源项目)必须是什么样子
我的想法如下:要求用户使用OpenID Connect进行身份验证。将凭据存储在cookie中,但之后不再依赖凭据,而是继续执行普通ApiResource使用引用令牌所做的操作->点击内省端点,检查令牌(从cookie中获取)是否有效,如果有效->允许访问,如果不可用->恢复到身份验证
遗憾的是,我根本无法让上述行为起作用。我不确定哪种模式适用于何处,尤其是cookies模式。如果我将其设置为默认模式,授权将通过,但是如果令牌被拒绝,我仍然可以访问资源,因为API仍然将cookie视为对令牌的引用,而实际上令牌已经被撤销。(内省将返回false)
对于托管Identity Server的项目,我不需要任何配置指针。我认为这样做的方法是使用隐式授权类型,如下所示:
new Client
{
ClientId = "Client_implicit",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Implicit,
AllowedScopes = new [] {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
},
AllowAccessTokensViaBrowser = true,
RedirectUris = new [] { "...Api Adress .../signin-oidc" },
PostLogoutRedirectUris = { "...Api Adress ../signout-callback-oidc" },
}
在Api启动类上:
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = "...IdentityServer Adress";
options.RequireHttpsMetadata = false;
options.ClientId = "Client_Implicit";
options.ClientSecret = "secret";
options.ResponseType = "id_token token";
options.Scope.Add("profile");
options.Scope.Add("openid");
options.GetClaimsFromUserInfoEndpoint = true;
options.SaveTokens = true;
});
在您的情况下,您不需要使用Api资源,因为您的客户机也是Api资源
要注销,请在api上创建注销操作,并包含以下内容:
await HttpContext.SignoutAsync("Cookie");
await HttpContext.SignoutAsync("OpenIdConnect");
因此,用于登录的senario将如下所示:
new Client
{
ClientId = "Client_implicit",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.Implicit,
AllowedScopes = new [] {
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
},
AllowAccessTokensViaBrowser = true,
RedirectUris = new [] { "...Api Adress .../signin-oidc" },
PostLogoutRedirectUris = { "...Api Adress ../signout-callback-oidc" },
}
- 用户将尝试登录
- api会将使用重定向到IdentityServer
- IdentityServer将检查用户凭据,并检查成功与否 重定向到具有(访问令牌)的api
- 用户现在登录
- 用户将调用注销李>
- access_令牌将从cookie和IdentityServer中删除