将声明存储到ASP.NET CORE 2.1中的COOKIE中

时间:2018-12-13 14:43:48

标签: openid-connect asp.net-core-2.1 httpcookie

身份验证成功后,我需要使用OpenID connect从Identity Provider身份验证用户,我需要将用户声明存储到cookie中。

但是我在Request.Cookies中找不到带有三个参数的append方法,我只能将keyvaluepair作为signle参数传递。

这是我的代码

public IActionResult Login(string provider, string returnUrl = null)
        {
             Challenge(new AuthenticationProperties { RedirectUri = returnUrl ?? "/" }, provider);
            Request.Cookies.Append("key", "value", new CookieOptions());

            return View();

 }

我还需要确认应该在哪里编写用于COOKIE存储的代码,以便一旦成功通过身份验证就无法再次存储它。

这是我的身份验证代码

services.AddAuthentication(options =>
            {
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;

            }).AddOpenIdConnect(options =>
                {
                    options.Authority = "https://accounts.google.com";
                    options.ClientId = _clientID;
                    options.ResponseType = "code id_token";
                    options.Scope.Add("openid");
                    options.Scope.Add("profile");
                    options.Scope.Add("email");
                    options.SaveTokens = true;
                    options.ClientSecret = _clientSecret;
                    //options.GetClaimsFromUserInfoEndpoint = true;
                    options.CallbackPath = "/home/index";
                    //options.SignedOutRedirectUri = redirectUrl;

                            options.Events = new OpenIdConnectEvents()
                            {
                                // handle the logout redirection 
                                OnRedirectToIdentityProviderForSignOut = context =>
                                {
                                    context.Response.Redirect(redirectUrl);
                                    context.HandleResponse();

                                    return Task.CompletedTask;
                                }
                            };


                        }).AddCookie(options => {
                            options.LoginPath = "/auth/signin";

                        });

提前谢谢。

1 个答案:

答案 0 :(得分:2)

不要将声明本身存储在cookie中,因为最终用户可以修改cookie。如果我修改Cookie并添加声明Role, Administrator(或您的应用程序中代表访问权限的任何概念),该怎么办?

使用提供的cookie处理程序在身份验证后存储声明。这就是使用模型的方式。 Cookie处理程序将对内容进行加密和签名,以防止其被篡改。

编辑后更新

借助DefaultSigninScheme,您已经使用代码将身份验证的结果存储在Cookie中。

您应该在后续请求中提供的User中提供可用的索赔。