首页 > 解决方案 > 使用 AddCookies 中间件时未生成 Cookie

问题描述

我正在尝试使用 AddCookie 中间件在我的应用程序中实现基于 cookie 的身份验证。这是我的示例。我有一个有两条路由的 web api 应用程序。

  1. 登录
  2. 获取详细信息

我的控制器方法看起来像这样。

 [HttpGet]
    [Route("login")]
    public IActionResult Login()
    {
        // un and pwd wll be validated here. skipped here for easy understanding.
        var clms = new List<Claim>();
        clms.Add(new Claim(ClaimTypes.Name, "myname"));
        clms.Add(new Claim(ClaimTypes.Email, "myname@test.com"));
        clms.Add(new Claim(ClaimTypes.MobilePhone, "123456"));

        var idty = new ClaimsIdentity(clms);

        var pri = new ClaimsPrincipal(idty );

        HttpContext.SignInAsync("Cookies", pri);

        return Redirect("/weatherforecast/getdetails");
      //  return Ok();

    }

    [HttpGet]
    [Authorize]
    [Route("getdetails")]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }

我的启动代码看起来像这样..

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication("Cookies").AddCookie("Cookies", ckie =>
        {
            ckie.Cookie.Name = "mysamplecookie";
           ckie.LoginPath = "/WeatherForecast/Login";
            
        });
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

当我在浏览器中输入登录路由时,会调用登录路由。但即使在登录后,此属性也始终返回 false。

HttpContext.User.Identity.IsAuthenticated;

此外,我的浏览器中也没有生成 cookie。请让我知道我错过了什么。

谢谢..

标签: authenticationcookiesmiddleware

解决方案


推荐阅读