aspnet core Identity
Contents [hide]
#身份认证和授权系统
成员管理
默认使用MSSQL
支持外部的Provider
使用ASP.NET Core Identity
- 登录和注册的View
-
Account Controller
-
Model
Asp.net core Identity重点类
- UserManager
- SignInManager
-需要使用的库Microsoft.AspNetCore.Identity.UI
步骤
添加一个AccountController类
- 添加对象SignInManager
private readonly SignInManager<IdentityUser> _signInManager
C#
- 添加对象UserManager
private readonly UserManager<IdentityUser> _userManager;
C#
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication4.ViewModels;
namespace WebApplication4.Controllers
{
public class AccountController : Controller
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly UserManager<IdentityUser> _userManager;
public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login(ViewModels.LoginViewModel loginViewModel)
{
if(!ModelState.IsValid)
{
return View(loginViewModel);
}
var user = await _userManager.FindByNameAsync(loginViewModel.UserName);
if(user!=null)
{
var result = await _signInManager.PasswordSignInAsync(user, loginViewModel.Password, false, false);
if(result.Succeeded)
{
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "用户名/或密码不正确");
return View(loginViewModel);
}
public IActionResult Register()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
{
if(ModelState.IsValid)
{
var user = new IdentityUser()
{
UserName = registerViewModel.UserName
};
var result = await _userManager.CreateAsync(user, registerViewModel.Password);
if(result.Succeeded)
{
return RedirectToAction("Index", "Home");
}
}
return View(registerViewModel);
}
[HttpPost]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");
}
}
}
C#
添加数据模型LoginViewModel
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace WebApplication4.ViewModels
{
public class LoginViewModel
{
[Required]
[Display(Name ="用户名")]
public string UserName { get; set; }
[Required]
[Display(Name = "密码")]
[DataType(DataType.Password)]
public string Password { get; set; }
}
}
C#
注册服务
services.AddDbContext<IdentityDbContext>(options =>
{
options.UseSqlServer(connectionString, b => b.MigrationsAssembly("WebApplication4"));
});
services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<IdentityDbContext>();
services.Configure<IdentityOptions>(options => {
options.Password.RequireDigit = false;
options.Password.RequiredLength = 0;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 0;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
});
C#
数据库迁移
Add-Migration initialIdentityDb -Context IdentityDbContext
update-database -Verbose -Context IdentityDbContextd
C#
在网页中注入代码
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<title>@ViewBag.Title</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
@if (SignInManager.IsSignedIn(User))
{
<form asp-controller="Account" asp-action="Logout" method="post" id="logoutForm">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a href="javascript:document.getElementById('logoutForm').submit()">登出</a>
</li>
</ul>
</form>
}
else
{
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a asp-controller="Account" asp-action="Register">注册</a>
</li>
<li class="nav-item">
<a asp-controller="Account" asp-action="Login">登录</a>
</li>
</ul>
}
</nav>
<div>
@RenderBody()
</div>
<hr />
@await Component.InvokeAsync("Welcome")
</body>
</html>
HTML
添加特性
在需要验证的函数上面增加[authorize]特性
[Authorize]
[HttpPost]
public IActionResult Add(Student model)
{
repository.Add(model);
return RedirectToAction("Index");
}
C#
具体流程
- 添加AccountController类
添加SignInManager<IdentityUser>属性和UserManager<IdentitUser>属性
C#
- 创建一个Login函数负责登录
- 创建服务
- 创建IdentityDbContext服务以及数据库迁移更新
- 创建默认的Identity服务
services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<IdentityBuilder>();
C#
- 修改密码设定
在服务中修改options关于密码要求的参数 - 添加中间件
app.UserAuthentication();
Filed under: ASP.NET Core,C#,编程 - @ 2022年4月10日 下午4:03