asp.net-core - 即使用户未登录,授权属性仍会成功传递
问题描述
美好的一天,我很困惑为什么即使我在我的控制器上使用 [Authorize] 属性,它也不会检查用户是否已登录并且仍然作为授权成功通过。我正在关注 Microsoft、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
{
}
这是具有 [Authorize] 属性的 Home Controller
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://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.0
我还将添加用于创建和处理防伪令牌的功能,以保护您的应用程序免受交叉伪造。
更新(解决方案):
此实现是已添加的 usign Identity,因此无需调用 AddAuthentication()
与此类似的问题:github.com/aspnet/AspNetCore/issues/4656
推荐阅读
- reactjs - React useState 选项值落后 onChange 选择 1 步
- android - 如何转换协程流
- > 列出
- javascript - 更新在渲染方法中调用的函数的状态值
- c# - 如何在读取 txt 文件时在 aspx 页面中添加项目符号?
- amazon-web-services - 何时明确使用 boto3 会话
- google-sheets - Google 表格中带 INT 的 SUMIFS
- html - 使第二个弹性列可滚动
- react-native - TypeError:Super 表达式必须为 null 或函数
- lazy-loading - 未映射和显式加载或延迟加载 EF Core
- javascript - 为什么表单提交多次输出相同的数据