属性授权总是返回false c#



我想通过属性Authorize来保护我的端点。但是他总是返回我登录页面,尽管SignInManager返回true这是我的代码'

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<DataBase>(options =>
{
options.UseSqlServer("Database string");
});

builder.Services.ConfigureApplicationCookie(cookie =>
{
cookie.ExpireTimeSpan = TimeSpan.FromMinutes(5);
cookie.LoginPath = "/Login/Login";
cookie.LogoutPath = "/Login/Logout";
cookie.AccessDeniedPath = "/Identity/Account/AccessDenied";
cookie.SlidingExpiration = true;
});

builder.Services.AddIdentity<User, Role>(
options =>
{
options.SignIn.RequireConfirmedAccount = false;
})
.AddEntityFrameworkStores<DataBase>().AddRoles<Role>().AddDefaultTokenProviders();

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

登录方法'

public async Task<ActionResult> Login(User.LoginUserModel userModel)
{
if (!ModelState.IsValid)
return Register(ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage).ToList());
var result = await _signInManager.PasswordSignInAsync(userModel.Email, userModel.Password, true, false);
if(!result.Succeeded)
return Login( new List<string>{ "User with this password and login does not exists" });
return Redirect("~/Home/Index");
}

我希望授权属性能够工作

您的代码以与预期相反的顺序调用app.UseAuthorization();app.UseAuthentication();

来自文档

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

UseRoutingUseAuthenticationUseAuthorization必须按照前面代码中的顺序调用。

如本文所述

身份验证是确定用户身份的过程。
授权是确定用户是否有权访问资源的过程。

您首先需要知道用户是谁,以便确定该用户被允许做什么。

最新更新