〔Authorize〕属性不能在asp.net核心web中工作



我在url中使用cookie身份验证:https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-5.0

我为用户成功使用HttpContext.SignInAsync,然后打开其他具有[Authorize]属性将其重定向到登录路径,并告诉我我没有登录。

为什么?

启动页面:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}

和服务:

services.AddRazorPages();
services.AddDbContext<Models.DBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("dbContext")));
services.AddScoped<Models.DBContext>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Manage/Login";
options.LogoutPath = "/Manage/Login";
options.ExpireTimeSpan = TimeSpan.FromMinutes(3600);
});

将代码更改为:

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

最新更新