简体   繁体   中英

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. My problems is why these cookies are generated?

Below statement, I take it from the Identity Server document. When identity server is configuring

IdentityServer internally calls both AddAuthentication and AddCookie with a custom scheme (via the constant IdentityServerConstants.DefaultCookieAuthenticationScheme),

Here why it calls AddCookies method on identity server itself?

Also when I configure Asp.net core web client to use Identity server authentication it also call AddCookie() method. 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

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. 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.

Your client applications may or may not need cookies depending on the architecture. 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.

IdentityServer doesn't do any of this. 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.

What you're doing here is essentially having the same app host both IdentityServer and a cookie auth-based frontend. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM