You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Web API:页面刷新后Session Cookie丢失及授权302问题

会话/Cookie认证问题求助

刚接触会话/Cookie认证,开发了一个Web API,包含登录端点和需有效Cookie才能访问的受保护端点,遇到以下问题:

  1. 受保护端点返回302错误:登录端点正常工作,能获取后端配置的Cookie,但前端点击按钮调用受保护端点时返回302 Found,会重定向到一个未设置的.NET默认端点。但用Postman测试时可正常访问该端点。
  2. Cookie刷新后消失:后端签发的Cookie在页面刷新后被删除,不清楚原因。

同时希望获得前后端安全处理会话认证的指导。

相关代码

认证配置(测试用短过期时间)

public static IServiceCollection AddApplicationCookieAuth(this IServiceCollection services) 
{
    services.AddAuthentication(options => {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options => {
            options.Cookie = new() {
                Name = "MySessionAuthCookie",
                HttpOnly = true
            };
            options.ExpireTimeSpan = TimeSpan.FromSeconds(30);
            options.SlidingExpiration = true;
        });

    return services;
}

控制器端点

// 受保护端点
[HttpGet]
[Authorize]
public IActionResult GetProtectedData() 
{
    return Ok("Protected data");
}

[HttpPost("login")]
public async Task<IActionResult> Login(LoginRequest request) 
{
    var user = await _userManager.FindByNameAsync(request.Email);

    if (user != null && await _userManager.CheckPasswordAsync(user, request.Password))
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Email, user.Email),
            new Claim(ClaimTypes.Role, "Admin")
        };

        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        
        var authProperties = new AuthenticationProperties { IsPersistent = true };

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

        return Ok("Login success");
    }

    return Unauthorized();
}

前端代码(HTML+JS)

async function protectedEndpoint() {
    try {
        const res = await axios.get("https://localhost:7009/api/auth", {withCredentials: true, });
        console.log('Response:', res);

    } catch(err) {
        console.error('Error:', err);
    }
}

async function authenticate(data) {
    try {
        const res = await axios.post("https://localhost:7009/api/auth/login", data, {withCredentials: true});
        console.log('Response:', res);
    } catch(err) {
        console.error('Error:', err);
    }
}

内容的提问来源于stack exchange,提问作者ServletException

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 18:15:22