当前位置: 首页 > news >正文

做外国的网站卖东西深圳正规网站建设服务

做外国的网站卖东西,深圳正规网站建设服务,简单的手机网页制作,农村未来10大暴利行业在 ASP.NET Core 应用中,基于 Cookie 的身份鉴权是一种常见的身份验证方式,特别适用于传统的 Web 应用程序。Cookie 能够在用户的浏览器中存储身份验证数据,从而在用户访问应用的不同页面时保持登录状态。 一、配置 Cookie 身份验证 首先&a…

在 ASP.NET Core 应用中,基于 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: "{controller=Home}/{action=Index}/{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 Task<IActionResult> Login(LoginViewModel model, string returnUrl = "/"){if (ModelState.IsValid){// 验证用户名和密码if (model.Username == "admin" && model.Password == "123456"){var claims = new List<Claim>{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 Task<IActionResult> Logout(){await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);return RedirectToAction("Index", "Home");}
}

创建 Login 视图

创建一个 Login.cshtml 视图,用于显示登录表单:

@model LoginViewModel<h2>Login</h2><form asp-action="Login" asp-route-returnUrl="@ViewData["ReturnUrl"]" method="post"><div asp-validation-summary="All" class="text-danger"></div><div class="form-group"><label asp-for="Username"></label><input asp-for="Username" class="form-control" /><span asp-validation-for="Username" class="text-danger"></span></div><div class="form-group"><label asp-for="Password"></label><input asp-for="Password" class="form-control" type="password" /><span asp-validation-for="Password" class="text-danger"></span></div><div class="form-group"><div class="checkbox"><label asp-for="RememberMe"><input asp-for="RememberMe" />@Html.DisplayNameFor(m => m.RememberMe)</label></div></div><button type="submit" class="btn btn-primary">Log 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 Task<IActionResult> Logout()
{await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);return RedirectToAction("Index", "Home");
}

总结

通过以上步骤,可以在 ASP.NET Core 应用中实现基于 Cookie 的身份鉴权,确保你的应用能够安全地验证用户身份并授权访问特定资源。Cookie 的持久性和易于管理的特性使其成为传统 Web 应用中身份验证的理想选择。

http://www.yayakq.cn/news/354311/

相关文章:

  • 定西模板型网站建设建设速干裤移动网站
  • 网站 改域名加盟商网站建设
  • 做网站是买服务器还是买主机网站建设规划书主题
  • 网站ip地址 转向域名商城网站开发代码案例
  • 绍兴网站专业制作常州网站建设方案
  • 河南国安建设集团有限公司信息网站360站长平台
  • 男女主网站上做的popo网络运营商有几家
  • 对网站建设培训的建议想要自己做一个网站怎么做
  • 制作企业网站是怎么收费的ps教学网站制作步骤
  • 企业建网站哪家好宁波网络营销推广制作
  • 北京网站制作工具wordpress简约模板下载
  • 静态网站注入wap版网站 加app提示
  • 文字游戏做的最好的网站河北邢台贴吧
  • 计算机应用网站建设与维护是做什么静态网页模板下载后怎么修改
  • 广州找工作哪个网站好企业歌曲制作
  • 网站备案所需材料手机排行榜网站
  • 建设网站的价格表做网站要多少费用
  • 安徽公路建设行业协会网站是哪个威海人才招聘网官网
  • 做网站 框架郑州网站建设及托管
  • 杭州开发区网站建设福州正规网站建设公司报价
  • 旅游网站开发文档怎么写惠州哪家做网站比较好
  • 网站建设 淄博外贸推广公司哪家好
  • 长春市长春网站建设哪家好广东海外建设监理有限公司网站
  • 企业建设官方网站的目的wordpress模块里加载最新文章
  • 云南省建设工程质量协会网站国际新闻头条最新热点新闻
  • 学做网站 空间 域名广州企业招聘
  • 大型网站建设推广微信电商小程序
  • 江苏建设部官方网站南阳网站seo顾问
  • 投资公司网站建设方案微信怎么弄公众号
  • 国内做网站群平台的公司免费ppypp网站