authentication - 使用 AddCookies 中间件时未生成 Cookie
问题描述
我正在尝试使用 AddCookie 中间件在我的应用程序中实现基于 cookie 的身份验证。这是我的示例。我有一个有两条路由的 web api 应用程序。
- 登录
- 获取详细信息
我的控制器方法看起来像这样。
[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。请让我知道我错过了什么。
谢谢..
解决方案
推荐阅读
- spring-boot - 如何对发出外部 WebClient 请求的类进行单元测试?
- string - Xcode 字符串搜索算法
- vba - 如何根据用户类型用相似的记录重新填充组合框
- node.js - 如何使用护照本地猫鼬更改用户名密码
- r - Ops.factor(host_neighbourhood, neighbourhood) 中的错误:因子的水平集不同
- php - php计算循环内的元素而不是循环外
- php - 上传 longblob 可以在本地工作,但不能在 Web 服务器上工作
- docker - 如何在使用 docker-compose 启动 webapp 之前填充 elasticsearch 数据库?
- php - 如何根据它的元素更改数组键
- php - 在 XML 文件中重新转义字符