我創建了一個 asp.net core 6 mvc web 應用程式。我沒有從一開始就添加用戶授權,而是在之后添加了 ASP.NET Core Identity。我的問題是,除了用戶尚未登錄時應重定向到的實際登錄頁面外,如何使所有頁面都受到密碼保護?這是我在 program.cs 中配置的東西還是我該怎么做?
這是我的program.cs檔案...
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
// Lockout settings.
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@ ";
options.User.RequireUniqueEmail = false;
});
// Add services to the container.
builder.Services.AddControllersWithViews();
var connectionString = builder.Configuration.GetConnectionString("AppDb");
builder.Services.AddDbContext<ApplicationDbContext>(x => x.UseSqlServer(connectionString));
builder.Services.AddIdentityCore<ApplicationUser>().AddEntityFrameworkStores<ApplicationDbContext>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/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.UseAuthorization();
app.UseAuthenticationCheck();
//app.UseAuthentication();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
更新我添加了這個中間件來檢查用戶是否經過身份驗證,如果沒有,他需要在登錄頁面上登錄。但它不起作用,因為我收到一條錯誤訊息,告訴我“localhost 將您重定向了太多次”。
這是我的中間件..
public class AuthenticationCheck
{
private readonly RequestDelegate _next;
public AuthenticationCheck(RequestDelegate next, ILoggerFactory logFactory)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
if (httpContext.User.Identity != null || !httpContext.User.Identity.IsAuthenticated)
{
httpContext.Response.Redirect("Login");
}
else
{
await _next(httpContext);
}
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class AuthenticationCheckExtensions
{
public static IApplicationBuilder UseAuthenticationCheck(this IApplicationBuilder builder)
{
return builder.UseMiddleware<AuthenticationCheck>();
}
}
我在這里錯過了什么......?
uj5u.com熱心網友回復:
為了實作這個目標,您可以使用該Authorized屬性。
如果您想將此規則應用于應用程式的所有路由并且不為您擁有的每個控制器/操作重復該屬性,您可以在中間件配置中定義它。為此,請更新您的路由,如下面的代碼
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
.RequireAuthorization();
這些為您的所有路由啟用授權。
RequireAuthorization適用于UseEndpoints、MapRazorPages和任何其他方法的方法。UseRouting改變這個之后,為了作業這個機制,你必須在中間件之后添加這個代碼塊。
app.UseAuthentication();
app.UseAuthorization();
這使您能夠處理Authentication和您的Authorization Policies.
畢竟,為了排除某些路由(如登錄頁面),Authentication您必須AllowAnonymous在控制器/操作上添加屬性
uj5u.com熱心網友回復:
是的,我現在添加了一個中間件,但是這個中間件出了點問題,因為我在瀏覽器中收到錯誤“localhost redirect you too many times”。我已經更新了上面的代碼。你能看到我做錯了什么嗎?
是的,它很明顯陷入,infinite loop因為它會檢查authentication并不斷失敗并繼續重定向。我想知道您是如此封閉,并且該場景是開箱即用的,這并不常見,其他貢獻者根本不了解您的要求。我們的計劃是不使用Authorize attribute因此,將限制用戶并最終重定向到登錄頁面。
解決方案:
中間件類:
public class ReverseAuthMiddleware
{
private readonly RequestDelegate _next;
public ReverseAuthMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
//bool isAuthorized = true;
var isAuthorized = httpContext.User.Claims.Any(c => c.Type != null && c.Value != null);
if (!isAuthorized && httpContext.Request.Path.Value != "/Login/Index")
{
httpContext.Response.Redirect("/Login/Index");
}
//If the user authenticated and the Path not login then we can Move forward into the pipeline
await _next(httpContext);
}
}
注意:讓我們解釋一下場景,我們必須考慮兩個場景,用戶必須登錄才能訪問任何頁面。因此,他可以訪問登錄頁面以防萬一,unauthorized user或者可以訪問任何頁面一次authenticated。因此,我們需要同時檢查authentication和which page he is trying to access其他,我們將進入forever loop. 此外。但是,我正在檢查httpContext.User.Claims,您的httpContext.User.Identity也很好。
程式.cs:
app.UseMiddleware<ReverseAuthMiddleware>();
輸出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/527957.html
