.net [未应用Authorize(Roles =“Manager”),其行为类似于AllowAnonymous

5us2dqdw  于 2023-05-19  发布在  .NET
关注(0)|答案(1)|浏览(121)

由于某种原因[Authorize]或[Authorize(Roles =“Manager”)]没有被应用,我得到了相同的结果。
我的代码是

` [Authorize(Roles = "Manager")]
    public void OnGet()
    {
      var x = User.IsInRole("Manager"); 
    }`

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
    .AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
;

builder.Services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
        options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
        options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
    })
    .AddCookie(options =>
    {
        options.LoginPath = "/Identity/Account/Login";
    });

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("AdminOnly", policy =>
        policy.RequireClaim("IsAdmin", "True"));

});

builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
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.UseAuthentication();
app.UseAuthorization();

using (var scope = app.Services.CreateScope())
{
    var serviceProvider = scope.ServiceProvider;
    await Seeder.Seed(serviceProvider);
}

app.MapRazorPages();

app.Run();
`public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}


谁都能看出这里的问题是什么,我错过了什么吗?
我希望被重定向到登录页面,以防我未被授权访问该页面,

eufgjt7s

eufgjt7s1#

[Authorize]
public class ProductsController : Controller
{
    public ActionResult View()
    {  }
    [Authorize(Roles = "Administrator,SuperAdmin")]
    public ActionResult Create()
    {   }
    [Authorize(Roles = "SuperAdmin")]
    public ActionResult Delete()
    {   }
    [Authorize(Roles = "Administrator")]
    [Authorize(Roles = "SuperAdmin")]
    public ActionResult SpecialFeature()
    {   }
}

相关问题