gpt4 book ai didi

c# - 授权(角色 = "Admin")总是返回拒绝访问

转载 作者:行者123 更新时间:2023-12-04 15:42:08 27 4
gpt4 key购买 nike

我花了很多时间在这件看似简单但找不到解决方案的事情上。

创建一个项目并运行良好,登录,注册等。但授权不适用于角色。创建和设置角色:

但是在尝试访问时总是返回拒绝访问:

public class _ConfigurationsController : Controller
{
[Authorize(Roles = "AdminApp")]
public IActionResult Index()
{
return View();
}
}

启动文件
...
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));

services.AddDbContext<Scaffolding_AutoGer_Context>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));

services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

app.UseAuthentication();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

在调试窗口中显示此消息:
...Authorization.DefaultAuthorizationService:Information: Authorization failed.
...: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
...: Executing ForbidResult with authentication schemes ().
...Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Identity.Application was forbidden.

AspNetRoles 表

enter image description here

AspNetUsers 表

enter image description here

AspNetUserRoles 表

enter image description here

MVC - 脚手架项目
个人账户登录
.NET 核心 2.1
VS 2017

更新:

登录类 - 自动生成

[允许匿名]
公共(public)类 LoginModel : PageModel
{
私有(private)只读 SignInManager _signInManager;
私有(private)只读 ILogger _logger;
public LoginModel(SignInManager<IdentityUser> signInManager, ILogger<LoginModel> logger)
{
_signInManager = signInManager;
_logger = logger;
}

[BindProperty]
public InputModel Input { get; set; }

public IList<AuthenticationScheme> ExternalLogins { get; set; }

public string ReturnUrl { get; set; }

[TempData]
public string ErrorMessage { get; set; }

public class InputModel
{
[Required]
[EmailAddress]
public string Email { get; set; }

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }

[Display(Name = "Memorizar?")]
public bool RememberMe { get; set; }
}

public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}

returnUrl = returnUrl ?? Url.Content("~/");

// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

ReturnUrl = returnUrl;
}

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");

if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
_logger.LogInformation("Usuário logado .");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("Conta bloqueada!");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Login inválido.");
return Page();
}
}

// If we got this far, something failed, redisplay form
return Page();
}

}

最佳答案

我认为您的问题与未配置策略有关。
public void ConfigureServices(IServiceCollection services)指定这些。

 services.AddAuthorization(options =>
options.AddPolicy("AdminApp",
policy => policy.RequireClaim("Manager")));

更多信息在这里。 https://docs.microsoft.com/en-us/aspnet/core/security/authorization/claims?view=aspnetcore-2.2

关于c# - 授权(角色 = "Admin")总是返回拒绝访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57486764/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com