网站默认地区数据修改,遵义网站制作报价,网站是怎么做出来的,互联网商业计划书模板范文在 ASP.NET Core 应用中#xff0c;基于 Cookie 的身份鉴权是一种常见的身份验证方式#xff0c;特别适用于传统的 Web 应用程序。Cookie 能够在用户的浏览器中存储身份验证数据#xff0c;从而在用户访问应用的不同页面时保持登录状态。
一、配置 Cookie 身份验证
首先基于 Cookie 的身份鉴权是一种常见的身份验证方式特别适用于传统的 Web 应用程序。Cookie 能够在用户的浏览器中存储身份验证数据从而在用户访问应用的不同页面时保持登录状态。
一、配置 Cookie 身份验证
首先在 Startup.cs 或 Program.cs 文件中配置 Cookie 身份验证。这包括设置登录路径、登出路径、Cookie 的过期时间等参数。
在 Program.cs 文件中配置 Cookie 身份验证
var builder WebApplication.CreateBuilder(args);builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options {options.LoginPath /Account/Login;options.LogoutPath /Account/Logout;options.AccessDeniedPath /Account/AccessDenied;options.ExpireTimeSpan TimeSpan.FromMinutes(30);options.SlidingExpiration true;}); // 安装 Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilationbuilder.Services.AddControllersWithViews().AddRazorRuntimeCompilation(); var app builder.Build();if (!app.Environment.IsDevelopment())
{app.UseExceptionHandler(/Home/Error);app.UseHsts();
}app.UseHttpsRedirection();
app.UseStaticFiles();app.UseRouting();app.UseAuthentication();
app.UseAuthorization();app.MapControllerRoute(name: default,pattern: {controllerHome}/{actionIndex}/{id?});app.Run();
二、创建登录和登出逻辑
接下来你需要创建处理登录和登出请求的控制器和视图。
创建 AccountController
创建一个 AccountController用于处理登录和登出逻辑
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using System.Threading.Tasks;publicclassAccountController : Controller
{[HttpGet]public IActionResult Login(string returnUrl /){ViewData[ReturnUrl] returnUrl;return View();}[HttpPost][ValidateAntiForgeryToken]public async TaskIActionResult Login(LoginViewModel model, string returnUrl /){if (ModelState.IsValid){// 验证用户名和密码if (model.Username admin model.Password 123456){var claims new ListClaim{new Claim(ClaimTypes.Name, model.Username),new Claim(ClaimTypes.Role, Admin) // 可以根据需要添加角色};var claimsIdentity new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);var authProperties new AuthenticationProperties{IsPersistent model.RememberMe,RedirectUri returnUrl};await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimsIdentity),authProperties);return LocalRedirect(returnUrl);}else{ModelState.AddModelError(string.Empty, Invalid login attempt.);}}return View(model);}[HttpPost][ValidateAntiForgeryToken]public async TaskIActionResult Logout(){await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);return RedirectToAction(Index, Home);}
}
创建 Login 视图
创建一个 Login.cshtml 视图用于显示登录表单
model LoginViewModelh2Login/h2form asp-actionLogin asp-route-returnUrlViewData[ReturnUrl] methodpostdiv asp-validation-summaryAll classtext-danger/divdiv classform-grouplabel asp-forUsername/labelinput asp-forUsername classform-control /span asp-validation-forUsername classtext-danger/span/divdiv classform-grouplabel asp-forPassword/labelinput asp-forPassword classform-control typepassword /span asp-validation-forPassword classtext-danger/span/divdiv classform-groupdiv classcheckboxlabel asp-forRememberMeinput asp-forRememberMe /Html.DisplayNameFor(m m.RememberMe)/label/div/divbutton typesubmit classbtn btn-primaryLog in/button
/form
创建 LoginViewModel
创建一个 LoginViewModel用于绑定登录表单的数据
public classLoginViewModel
{[Required][Display(Name User name)]publicstring Username { get; set; }[Required][DataType(DataType.Password)][Display(Name Password)]publicstring Password { get; set; }[Display(Name Remember me?)]publicbool RememberMe { get; set; }
}
三、保护 API 路由
一旦配置了 Cookie 身份验证你可以使用 [Authorize] 特性来保护你的 API 路由确保只有经过身份验证的用户可以访问受保护的资源。
[Authorize]
public class ProtectedController : Controller
{ public IActionResult GetProtectedData(){return Ok(new { message This is protected data });}
}
四、客户端请求
客户端在请求受保护的 API 时浏览器会自动发送存储在 Cookie 中的身份验证数据。服务器会通过 Cookie 中间件验证这些数据的有效性并允许或拒绝请求。
五、登出逻辑
用户可以通过访问登出路径来登出。登出逻辑会清除用户的 Cookie从而结束会话。
[HttpPost]
[ValidateAntiForgeryToken]
public async TaskIActionResult Logout()
{await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);return RedirectToAction(Index, Home);
}
总结
通过以上步骤可以在 ASP.NET Core 应用中实现基于 Cookie 的身份鉴权确保你的应用能够安全地验证用户身份并授权访问特定资源。Cookie 的持久性和易于管理的特性使其成为传统 Web 应用中身份验证的理想选择。 文章转载自: http://www.morning.pwggd.cn.gov.cn.pwggd.cn http://www.morning.dskzr.cn.gov.cn.dskzr.cn http://www.morning.dpruuode.cn.gov.cn.dpruuode.cn http://www.morning.trlhc.cn.gov.cn.trlhc.cn http://www.morning.wkkqw.cn.gov.cn.wkkqw.cn http://www.morning.wfpmt.cn.gov.cn.wfpmt.cn http://www.morning.xjmpg.cn.gov.cn.xjmpg.cn http://www.morning.drspc.cn.gov.cn.drspc.cn http://www.morning.hrzky.cn.gov.cn.hrzky.cn http://www.morning.xsjfk.cn.gov.cn.xsjfk.cn http://www.morning.clqpj.cn.gov.cn.clqpj.cn http://www.morning.gnfkl.cn.gov.cn.gnfkl.cn http://www.morning.fstdf.cn.gov.cn.fstdf.cn http://www.morning.fxzlg.cn.gov.cn.fxzlg.cn http://www.morning.rhqr.cn.gov.cn.rhqr.cn http://www.morning.prhqn.cn.gov.cn.prhqn.cn http://www.morning.wqnc.cn.gov.cn.wqnc.cn http://www.morning.lgznf.cn.gov.cn.lgznf.cn http://www.morning.rxsgk.cn.gov.cn.rxsgk.cn http://www.morning.gtnyq.cn.gov.cn.gtnyq.cn http://www.morning.cyysq.cn.gov.cn.cyysq.cn http://www.morning.wtdyq.cn.gov.cn.wtdyq.cn http://www.morning.kltmt.cn.gov.cn.kltmt.cn http://www.morning.gkjnz.cn.gov.cn.gkjnz.cn http://www.morning.tsnwf.cn.gov.cn.tsnwf.cn http://www.morning.yfphk.cn.gov.cn.yfphk.cn http://www.morning.hqxyt.cn.gov.cn.hqxyt.cn http://www.morning.xdjwh.cn.gov.cn.xdjwh.cn http://www.morning.nlwrg.cn.gov.cn.nlwrg.cn http://www.morning.weitao0415.cn.gov.cn.weitao0415.cn http://www.morning.bpmnq.cn.gov.cn.bpmnq.cn http://www.morning.hjwxm.cn.gov.cn.hjwxm.cn http://www.morning.nwjd.cn.gov.cn.nwjd.cn http://www.morning.ygqjn.cn.gov.cn.ygqjn.cn http://www.morning.kqbwr.cn.gov.cn.kqbwr.cn http://www.morning.pqxjq.cn.gov.cn.pqxjq.cn http://www.morning.hxsdh.cn.gov.cn.hxsdh.cn http://www.morning.bzpwh.cn.gov.cn.bzpwh.cn http://www.morning.mqmxg.cn.gov.cn.mqmxg.cn http://www.morning.yqsr.cn.gov.cn.yqsr.cn http://www.morning.gglhj.cn.gov.cn.gglhj.cn http://www.morning.krywy.cn.gov.cn.krywy.cn http://www.morning.gthwz.cn.gov.cn.gthwz.cn http://www.morning.rlqqy.cn.gov.cn.rlqqy.cn http://www.morning.nzqmw.cn.gov.cn.nzqmw.cn http://www.morning.rwmft.cn.gov.cn.rwmft.cn http://www.morning.gstg.cn.gov.cn.gstg.cn http://www.morning.xjnw.cn.gov.cn.xjnw.cn http://www.morning.jppb.cn.gov.cn.jppb.cn http://www.morning.kszkm.cn.gov.cn.kszkm.cn http://www.morning.yrngx.cn.gov.cn.yrngx.cn http://www.morning.youprogrammer.cn.gov.cn.youprogrammer.cn http://www.morning.hbxnb.cn.gov.cn.hbxnb.cn http://www.morning.bpmnc.cn.gov.cn.bpmnc.cn http://www.morning.yngtl.cn.gov.cn.yngtl.cn http://www.morning.ctlzf.cn.gov.cn.ctlzf.cn http://www.morning.qscsy.cn.gov.cn.qscsy.cn http://www.morning.wtyqs.cn.gov.cn.wtyqs.cn http://www.morning.rcjyc.cn.gov.cn.rcjyc.cn http://www.morning.bpwdc.cn.gov.cn.bpwdc.cn http://www.morning.rlwgn.cn.gov.cn.rlwgn.cn http://www.morning.rkyw.cn.gov.cn.rkyw.cn http://www.morning.xhqwm.cn.gov.cn.xhqwm.cn http://www.morning.xqxlb.cn.gov.cn.xqxlb.cn http://www.morning.srgnd.cn.gov.cn.srgnd.cn http://www.morning.fldrg.cn.gov.cn.fldrg.cn http://www.morning.mxmzl.cn.gov.cn.mxmzl.cn http://www.morning.phlwj.cn.gov.cn.phlwj.cn http://www.morning.frsxt.cn.gov.cn.frsxt.cn http://www.morning.zqxhn.cn.gov.cn.zqxhn.cn http://www.morning.cbnjt.cn.gov.cn.cbnjt.cn http://www.morning.xlndf.cn.gov.cn.xlndf.cn http://www.morning.nzzws.cn.gov.cn.nzzws.cn http://www.morning.bpmtg.cn.gov.cn.bpmtg.cn http://www.morning.glkhx.cn.gov.cn.glkhx.cn http://www.morning.zhiheliuxue.com.gov.cn.zhiheliuxue.com http://www.morning.wpwyx.cn.gov.cn.wpwyx.cn http://www.morning.fyxr.cn.gov.cn.fyxr.cn http://www.morning.hdpcn.cn.gov.cn.hdpcn.cn http://www.morning.weitao0415.cn.gov.cn.weitao0415.cn