简体   繁体   English

如何制作一种方法来验证 cookie 身份验证? ASP.NET 核心 3.1

[英]how to made a method to validate a cookie authentication? asp.net core 3.1

I've tried make a method to to validate a cookie authentication but appear this error: Error我尝试制作一种方法来验证 cookie 身份验证,但出现此错误:错误

I've tried use this:我试过用这个:

public int CookieValidation()
    {
        int answer = 0;

        
        string CookieSession = HttpContext.Session.GetString("SesionSecondApp");

        if(!String.IsNullOrEmpty(CookieSession))
        {
            answer = 1;
        }
        

        return answer;
    }
}

I made a cookie authentication:我做了一个cookie认证:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.Cookie.Name = "SesionSecondApp";
                options.ExpireTimeSpan = TimeSpan.FromDays(7);
                options.Cookie.SameSite = SameSiteMode.Lax;

            });

Use this claims:使用此声明:

var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Email, email),
            new Claim(ClaimTypes.Role, role),
        };

        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        var principal = new ClaimsPrincipal(identity);
        var props = new AuthenticationProperties();

        HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, props);

In the browser, cookie stores the authentication configuration that has been added in the server.在浏览器中,cookie 存储了服务器中已经添加的认证配置。 SesionSecondApp cannot be obtained from the session here, because you did not configure session. SesionSecondApp无法从会话中获取SesionSecondApp ,因为您没有配置会话。

在此处输入图片说明

The correct way to get SesionSecondApp is this code.获取SesionSecondApp的正确方法是此代码。

public int CookieValidation()
    {
        int answer = 0;
        var getCookie = "";
        HttpContext.Request.Cookies.TryGetValue("SesionSecondApp", out getCookie);
        //...
        return answer;
    }

Result:结果: 在此处输入图片说明

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

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