1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Asp.Net Core 实现登录验证身份的功能

Asp.Net Core 实现登录验证身份的功能

时间:2021-11-10 03:43:36

相关推荐

Asp.Net Core 实现登录验证身份的功能

步骤如下:

1.打开VS,新建 Core Web应用程序,选择Web应用程序(模型视图控制器)

不用勾选右侧的身份认证,因为演示的是比较简单的,而勾选之后模板内容较为复杂

2、在Controller文件夹下AccountController,代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Security.Claims;using System.Threading.Tasks;using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authentication.Cookies;using Microsoft.AspNetCore.Authorization;using Microsoft.AspNetCore.Mvc;namespace Server.Controllers{public class AccountController: Controller{/// <summary>/// 登录页面/// </summary>/// <returns></returns>public IActionResult Login(){return View();}/// <summary>/// post 登录请求/// </summary>/// <returns></returns>[HttpPost]public async Task<IActionResult> Login(string userName, string password){if (userName.Equals("admin") && password.Equals("123456")){var claims = new List<Claim>(){new Claim(ClaimTypes.Name,userName),new Claim("password",password)};var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties{ExpiresUtc = DateTime.UtcNow.AddMinutes(20),IsPersistent = false,AllowRefresh = false});return Redirect("/Home/Index");}return Json(new { result = false, msg = "用户名密码错误!" });}/// <summary>/// 退出登录/// </summary>/// <returns></returns>public async Task<IActionResult> Logout(){await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);return Redirect("/Login");}}}

3.在Views文件夹下新建一个Account的文件夹,并在文件夹中新建Login.cshtml,实现登录页面的html视图

内容如下:

@{ViewData["Title"] = "登录";}<h2 style="text-align:center">登录管理系统</h2><hr /><div><form asp-controller="Account" asp-action="Login" method="post"><div><label class="control-label">用户名</label><input class="form-control" type="text" name="username"/></div><div><label class="control-label">密码</label><input class="form-control" type="password" name="password" /></div><div class="form-group"><input type="submit" value="登录" class="btn btn-primary" /></div></form></div>@section Scripts {@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}}

4.修改Startup.cs文件内容,将身份认证中间件添加到容器中

在public void ConfigureServices(IServiceCollectionservices)方法中加入如下内容:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>{//登录路径:这是当用户试图访问资源但未经过身份验证时,程序将会将请求重定向到这个相对路径o.LoginPath = new PathString("/Account/Login");//禁止访问路径:当用户试图访问资源时,但未通过该资源的任何授权策略,请求将被重定向到这个相对路径。o.AccessDeniedPath = new PathString("/Home/Privacy");});

在public void Configure(IApplicationBuilderapp,Microsoft.AspNetCore.Hosting.IHostingEnvironmentenv) 方法中加入:

app.UseAuthentication();//认证//身份验证中间件注意这句话要放在app.UseMvc的前面

5.F5运行项目,然后在浏览器中输入:

https://localhost:5000/Account/Login,访问登录界面

输入账号密码后,点击登录,则会进入AccountController的post Login方法,进行验证,若验证成功,则会调用HttpContext.SignInAsync 方法给浏览器发送一个cookie的认证信息

这样用户就可以在其他页面中使用该认证信息进行访问了

6.如何控制呢?

通过注解[Authorize] ,在所有需要用户登录的Controller上方加上[Authorize]注解,那么由于在startup中注册过的原因,若发现用户没有认证信息,则会跳转到Account/Login 登录页面要求登录

由于已经在Controller上方加过[Authorize],因此这个Controller中所有的方法都会要求验证,如果在该Controller中又有一个get api,我们想让其不需要验证就可以访问,那么可以在该方法上方加上[AllowAnonymous],如:

[AllowAnonymous][HttpGet][Route("/info")]public ActionResult<string> Get(){return serviceImpl.getDataAll();}

同理[AllowAnonymous]也可以加在Controller上方

这样就实现了.netCore 简单的身份验证以及登录功能

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。