c#.net 6.0我可以离开饼干

发布于 2025-02-12 01:10:06 字数 1392 浏览 1 评论 0原文

我正在通过React登录过程发送用户名和密码。如果用户名和密码正确,我希望用户的浏览器将令牌设置为cookie。但这不会抛出。

[HttpPost("[action]")]
        public async Task<ActionResult<Token>> Login( UserLogin userLogin)
        {
            User user = await context.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).FirstOrDefaultAsync(x=>x.Email == userLogin.Email && x.Password == userLogin.Password);
            
            if(user != null)
            {
                TokenHandler tokenHandler = new TokenHandler(configuration);
                Token token = tokenHandler.CreateAccessToken(user);
                user.RefreshToken = token.RefreshToken;
                user.RefrestTokenEndDate = token.Expiration.AddMinutes(3);
                await context.SaveChangesAsync();


                var cookieOptions = new CookieOptions
                {
                    HttpOnly = true,
                    Expires = DateTime.UtcNow.AddHours(8),
                    Path = "/login"
                };
                Response.Cookies.Append("RefreshToken", token.RefreshToken, cookieOptions);
                Response.Cookies.Append("AccessToken", token.AccessToken, cookieOptions);

                return Ok(token);
            }

            return null;
        }

登录地址:http:// localhost:3000/login

令牌和验证过程没有任何问题。饼干部分有问题...

I am sending username and password by react for login process. If the username and password are correct, I want the user's browser to set the token as a cookie. but it doesn't throw.

[HttpPost("[action]")]
        public async Task<ActionResult<Token>> Login( UserLogin userLogin)
        {
            User user = await context.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).FirstOrDefaultAsync(x=>x.Email == userLogin.Email && x.Password == userLogin.Password);
            
            if(user != null)
            {
                TokenHandler tokenHandler = new TokenHandler(configuration);
                Token token = tokenHandler.CreateAccessToken(user);
                user.RefreshToken = token.RefreshToken;
                user.RefrestTokenEndDate = token.Expiration.AddMinutes(3);
                await context.SaveChangesAsync();


                var cookieOptions = new CookieOptions
                {
                    HttpOnly = true,
                    Expires = DateTime.UtcNow.AddHours(8),
                    Path = "/login"
                };
                Response.Cookies.Append("RefreshToken", token.RefreshToken, cookieOptions);
                Response.Cookies.Append("AccessToken", token.AccessToken, cookieOptions);

                return Ok(token);
            }

            return null;
        }

login adress: http://localhost:3000/login

The token and verification process works without any issues. There is a problem with the cookie part...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦在深巷 2025-02-19 01:10:06

恐怕您使用React创建一个前端应用程序和.NET 6来创建服务器后端,因此端口彼此不同。因此,您可以在.NET 6应用程序中设置CORS策略。

这是我的一些假设。首先,您可以尝试此cookieoption并进行测试,了解 samesitemode

var cookieOptions = new CookieOptions
{
    HttpOnly = true,
    Expires = DateTime.UtcNow.AddHours(8),
    //Path = "localhost",
    SameSite = SameSiteMode.None,
    Secure = true
};

我在我的身边进行了测试,并使用了这样的ajax请求

$("#btn1").click(function() {
    $.ajax({
        url: "https://localhost:7016/",
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            alert(data);
        }
    })
});

,我的cors策略:

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "my",
       policy =>
       {
 policy.WithOrigins("http://localhost:8848").AllowAnyHeader().AllowAnyMethod().AllowCredentials();
       });
});

I'm afraid you used React to create a frontend app and .net 6 to create the server backend, so the port are different with each other. So you may set Cors policy in your .net 6 application.

Here's some of my assumption. Firstly, you may try this cookieOption and have a test, learn about SameSiteMode:

var cookieOptions = new CookieOptions
{
    HttpOnly = true,
    Expires = DateTime.UtcNow.AddHours(8),
    //Path = "localhost",
    SameSite = SameSiteMode.None,
    Secure = true
};

I did a test in my side with an ajax request like this

$("#btn1").click(function() {
    $.ajax({
        url: "https://localhost:7016/",
        xhrFields: {
            withCredentials: true
        },
        success: function(data) {
            alert(data);
        }
    })
});

And my cors policy:

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "my",
       policy =>
       {
 policy.WithOrigins("http://localhost:8848").AllowAnyHeader().AllowAnyMethod().AllowCredentials();
       });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文