步骤如下:
1.打开VS2019,新建ASP.NET 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
{
///
/// 登录页面
///
///
public IActionResult Login()
{
return View();
}
///
/// post 登录请求
///
///
[HttpPost]
public async Task Login(string userName, string password)
{
if (userName.Equals("admin") && password.Equals("123456"))
{
var claims = new List(){
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 = "用户名密码错误!" });
}
///
/// 退出登录
///
///
public async Task Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/Login");
}
}
}
3.在Views文件夹下新建一个Account的文件夹,并在文件夹中新建Login.cshtml,实现登录页面的html视图
内容如下:
@{
ViewData["Title"] = "登录";
}
登录管理系统
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
4.修改Startup.cs文件内容,将身份认证中间件添加到容器中
在public void ConfigureServices(IServiceCollection services)方法中加入如下内容:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
{
//登录路径:这是当用户试图访问资源但未经过身份验证时,程序将会将请求重定向到这个相对路径
o.LoginPath = new PathString("/Account/Login");
//禁止访问路径:当用户试图访问资源时,但未通过该资源的任何授权策略,请求将被重定向到这个相对路径。
o.AccessDeniedPath = new PathString("/Home/Privacy");
});
在public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env) 方法中加入:
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 Get()
{
return serviceImpl.getDataAll();
}
同理[AllowAnonymous]也可以加在Controller上方
这样就实现了.netCore 简单的身份验证以及登录功能