MVC [授权] 属性适用于除主页以外的每个页面



我在 .Net Core 2.1 Web 应用程序中使用 cookie 身份验证,但我似乎无法让授权属性在默认主页(网络应用程序 URL(上工作。该属性在所有其他页面上都有效。

当我转到 https://appurl/home 时,它会重定向到登录,但导航到 https://appurl 根本不需要身份验证。这是我的启动路由:

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

这是我的家庭控制器:

[Authorize]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}

所有其他标有 [授权] 的控制器都像这样重定向按预期登录,我只是不知道如何在默认应用程序 url 上指定授权。

任何帮助将不胜感激。

更新:我想我已经解决了我的问题,基本上默认要求身份验证并允许匿名访问我的登录剃须刀片页面(我同时使用 mvc 和剃须刀片页面(。我仍然很好奇是否可以以另一种方式完成,但这是我的创业公司.cs:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
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.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddRazorPagesOptions(options =>
{
options.Conventions.AllowAnonymousToPage("/Account/Login");
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
});
// Add DB contexts here.
services.Configure<Database.DatabaseConfig>(Configuration.GetSection("ConnectionStrings"));
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
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?}");
});
}
}

您似乎忘记在下面添加services.AddAuthorization ();services.AddAuthentication (...);

如果你这样做,你可能不需要这个:

services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddRazorPagesOptions(options =>
{
options.Conventions.AllowAnonymousToPage("/Account/Login");
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

您可以为此进行更改:

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

最新更新