祝你好运,我很困惑,为什么即使我在控制器上使用了[Authorize]属性,它也不会检查用户是否登录并仍然通过授权。我正在学习微软、HERE和HERE的基本身份和授权教程。我可以进行基本的身份验证,创建用户并登录等等,但授权只允许访客通过,系统会错误地将他们识别为成功。我使用chrome进行测试,所以我甚至使用私人模式,并在存储信息时清除cookie和缓存。我完全被难住了,我不知道还能做什么。
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息:授权成功。
是我在调试控制台日志中得到的授权成功消息。
下面是Startup.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.AddRazorPages();
services.AddControllersWithViews();
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
});
services.AddDbContext<DevContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<UserContext>(options => options.UseSqlServer(Configuration.GetConnectionString("UserContextConnection")));
services.AddIdentity<User, IdentityRole>().AddEntityFrameworkStores<UserContext>().AddDefaultTokenProviders();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.ConfigureApplicationCookie(options =>
{
//Cokie Settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromDays(150);
//If the LoginPath isn't set, ASP.NET Core defaults the path to Account/Login.
// options.LoginPath = "/Account/Login";
// options.AccessDeniedPath = "/Account/AccessDenied";
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Identity/Account/Logout";
options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
// services.AddSingleton<IEmailSender, EmailSender> ();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
endpoints.MapDefaultControllerRoute().RequireAuthorization();
}
);
}
}
下面是User.cs,将其留空,因为基本演示没有任何自定义字段,它仍然有效。所以我不确定这会是个问题。
public class User : IdentityUser
{
}
这是具有[授权]属性的主控制器
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[Authorize]
public IActionResult Information()
{
ViewData["Message"] = "Test Information Page";
return View();
}
[Authorize]
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
[Authorize]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
[Authorize]
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
我认为你的问题是这一行:
services.AddAuthentication(IISDefaults.AuthenticationScheme);
这意味着你的应用程序将使用你的windows登录来验证你,而不是你创建的cookie。
我会把它改成这个,因为你使用的是基于cookie的身份验证方案:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
请参阅以下指南:
https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.0
我还将添加创建和处理防伪造令牌的功能,以保护您的应用程序免受交叉伪造。
更新(解决方案(:
此实现是已经添加的usingn Identity,因此无需调用AddAuthentication((
与此类似的问题:github.com/aspnet/AspNetCore/issues/4566