要实现ASP.NET Core中的[Authorize]要求用户在最近登录的页面上进行登录,可以按照以下步骤进行操作:
public void ConfigureServices(IServiceCollection services)
{
// 添加身份验证服务
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/Account/Login"; // 设置登录路径
options.ExpireTimeSpan = TimeSpan.FromMinutes(60); // 设置Cookie过期时间
});
// 添加授权策略
services.AddAuthorization();
// 其他服务配置...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 其他配置...
// 启用身份验证中间件
app.UseAuthentication();
// 启用授权中间件
app.UseAuthorization();
// 其他配置...
}
[Authorize]
public class HomeController : Controller
{
// 控制器代码...
}
SignInAsync方法将用户标识写入Cookie,例如:[HttpPost]
public async Task Login(LoginViewModel model)
{
// 验证用户输入...
// 如果验证通过,使用SignInAsync方法登录用户
var claims = new List
{
new Claim(ClaimTypes.NameIdentifier, model.UserId),
new Claim(ClaimTypes.Name, model.UserName)
// 其他用户相关的Claim
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(principal);
// 登录成功后的逻辑...
return RedirectToAction("Index", "Home");
}
这样,当用户访问需要授权的页面时,如果未登录或者登录已过期,系统会自动跳转到登录页面进行登录。登录成功后,用户将被重定向回原来要访问的页面。