简体   繁体   English

为什么要使用Identity Server和asp.net core 2在基于令牌的身份验证上使用cookie

[英]Why having cookies on token based authentication using Identity Server and asp.net core 2

I am creating a sample application to just to understand how identity server 4 authentication works with Asp.net core 2. I have noticed some cookies are generated for different levels as it can be seen in the attached screenshot. 我正在创建一个示例应用程序,只是为了了解身份服务器4身份验证如何与Asp.net core 2一起工作。我注意到有些Cookie是针对不同级别生成的,如所附的屏幕截图所示。 My problems is why these cookies are generated? 我的问题是为什么生成这些cookie?

Below statement, I take it from the Identity Server document. 在下面的语句中,我将其从Identity Server文档中获取。 When identity server is configuring 身份服务器配置时

IdentityServer internally calls both AddAuthentication and AddCookie with a custom scheme (via the constant IdentityServerConstants.DefaultCookieAuthenticationScheme), IdentityServer在内部使用自定义方案(通过常量IdentityServerConstants.DefaultCookieAuthenticationScheme)调用AddAuthentication和AddCookie,

Here why it calls AddCookies method on identity server itself? 在这里为什么要在身份服务器本身上调用AddCookies方法?

Also when I configure Asp.net core web client to use Identity server authentication it also call AddCookie() method. 同样,当我配置Asp.net核心Web客户端以使用身份服务器身份验证时,它也会调用AddCookie()方法。 When I try to comment it It will give me an error. 当我尝试发表评论时,它会给我一个错误。 I am bit of unclear what is happening here. 我不清楚这里发生了什么。

Identity Server Configurations 身份服务器配置

services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddToDoUserStore()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients());

            services.AddAuthentication("MyCookie")
            .AddCookie("MyCookie", options =>
            {
                options.ExpireTimeSpan = new System.TimeSpan(0, 0, 15);
            });

Web Client Configuration Web客户端配置

services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect(options =>
            {
                options.Authority = "https://localhost:44377/";
                options.RequireHttpsMetadata = true;
                options.ClientId = "ToDoTaskManagmentClient";
                options.Scope.Clear();
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("address");
                options.Scope.Add("roles");
                options.Scope.Add("usertodoapi");
                options.Scope.Add("countries");
                options.Scope.Add("subscriptionlevel");
                options.Scope.Add("offline_access");
                options.ResponseType = "code id_token";
                options.SaveTokens = true;
                options.ClientSecret = "secret";
                options.GetClaimsFromUserInfoEndpoint = true;
                options.ClaimActions.Clear();
                options.ClaimActions.MapJsonKey("given_name", "given_name");
                options.ClaimActions.MapJsonKey("family_name", "family_name");
                options.ClaimActions.MapJsonKey("role", "role");
                options.ClaimActions.MapJsonKey("country", "country");
                options.ClaimActions.MapJsonKey("subscriptionlevel", "subscriptionlevel");
                options.Events = new OpenIdConnectEvents()
                {
                    OnTokenValidated = e =>
                    {
                        var identity = e.Principal;
                        var subjectClaim = identity.Claims.FirstOrDefault(z => z.Type == "sub");
                        var expClaims = identity.Claims.FirstOrDefault(z => z.Type == "exp");
                        var newClaimsIdentity = new ClaimsIdentity(e.Scheme.Name);
                        newClaimsIdentity.AddClaim(subjectClaim);
                        newClaimsIdentity.AddClaim(expClaims);

                        e.Principal = new ClaimsPrincipal(newClaimsIdentity);
                        return Task.FromResult(0);
                    },
                    OnUserInformationReceived = e =>
                    {
                        e.User.Remove("address");
                        return Task.FromResult(0);
                    }
                };
            });

在此处输入图片说明

Your Identity Server application needs an authentication cookie (and session ID cookie) so that the front channel endpoints (authorize, consent, check_session_iframe and possibly others) know if the user is authenticated or not and the current state of the session. 您的Identity Server应用程序需要身份验证cookie(和会话ID cookie),以便前端通道端点(授权,同意,check_session_iframe以及可能的其他消息)知道用户是否已通过身份验证以及会话的当前状态。 Without this it would have no idea who was calling it. 没有这个,就不会知道谁在叫它。 IDS4 will automatically redirect to the login URL of the default scheme if it detects that the incoming request is not authenticated - you are then free to implement any authentication flow you like. 如果IDS4检测到传入请求未通过身份验证,它将自动重定向到默认方案的登录URL-然后您可以自由地实施所需的任何身份验证流程。

Your client applications may or may not need cookies depending on the architecture. 根据体系结构,您的客户端应用程序可能需要cookie,也可能不需要。 A traditional server side WebForms or MVC-style app will need one but a pure JS client using a library like oidc-client-js will not and can talk to the back-end purely using the access token obtained from your identity server. 传统的服务器端WebForms或MVC风格的应用程序将需要一个,但使用oidc-client-js之类的库的纯JS客户端将不需要,并且可以纯粹使用从身份服务器获取的访问令牌与后端进行对话。

IdentityServer doesn't do any of this. IdentityServer不执行任何操作。 All it does is handle the low-level authentication/authorization and return a claims principal. 它所做的只是处理低级别的身份验证/授权并返回声明主体。 Your application that's using IdentityServer is the one that would set the cookie. 您使用IdentityServer的应用程序就是设置cookie的应用程序。

What you're doing here is essentially having the same app host both IdentityServer and a cookie auth-based frontend. 您在这里所做的本质上是让同一服务器托管IdentityServer和基于cookie auth的前端。 The cookie portion is for the traditional login flow UI, so that the app can recognize whether the user is authenticated and redirect to a login form or to an account page or back to the originating app, if or when they are authenticated. Cookie部分用于传统的登录流程UI,因此该应用程序可以识别用户是否已通过身份验证,如果经过身份验证或何时进行身份验证,则可以重定向到登录表单或帐户页面或重定向回原始应用程序。

That piece could be completely spun-off into a totally different app, and then your IdentityServer app would no longer need the cookie auth config. 可以将其完全拆分成一个完全不同的应用程序,然后您的IdentityServer应用程序将不再需要cookie auth配置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core 3 with Angular 8, ASP.NET Core Identity, Roles and token based authentication - ASP.NET Core 3 with Angular 8, ASP.NET Core Identity, Roles and token based authentication 在WebAPI和asp.net核心中使用基于Cookie的身份验证 - Using Cookies based authentication in WebAPI and asp.net core 使用ASP.NET Core身份验证和基于令牌的身份验证时,为什么要登录新用户? - Why sign-in a new user when using ASP.NET Core Identity and token-based auth? Identity Server 4(2.0)不读取Asp.Net核心标识cookie - Identity Server 4 (2.0) not reading Asp.Net Core Identity cookies ASP.NET Core身份验证中的两个身份验证cookie - Two authentication cookies in ASP.NET Core Identity ASP.NET Core 中基于令牌的身份验证 - Token Based Authentication in ASP.NET Core 带有ASP.NET CORE 1.0的Identity Server 3身份验证/授权 - Identity Server 3 Authentication/Authorization, with ASP.NET CORE 1.0 Asp net Core Identity 令牌认证过期 - Asp net Core Identity token authentication expiration 检查用户是否使用ASP.NET Core中的基于令牌的身份验证登录 - Check if user is logged in with Token Based Authentication in ASP.NET Core ASP.NET核心中基于令牌的身份验证(刷新) - Token Based Authentication in ASP.NET Core (refreshed)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM