类库组件
.NET Core的身份认证使用的类库如下图:常用的
Microsoft.AspNetCore.Authorization
Microsoft.AspNetCore.Authorization.Cookies
Microsoft.AspNetCore.Authorization.OpenIdConnect
Microsoft.AspNetCore.Authorization.OAuth
演示下基于Cookies的
Startup.cs添加管道支持:
ConfigureService:
services.AddAuthorization();
Configure:
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie", LoginPath = new PathString("/Account/Login"), AccessDeniedPath = new PathString("/Account/Forbidden"), AutomaticAuthenticate = true, AutomaticChallenge = true });
环境支持配置完以后;老套路简单使用一下
Controller或者Action添加[Authorize];Claim声明一些属性,加入到ClaimIdentity(IIdentity)属性标识;通过ClaimIdentity再创建身份ClaimPrincipal(IPrincipal)出来;存入Cookie
AccountController :
public class AccountController : Controller { [Authorize] // GET: /<controller>/ public IActionResult Index() { return View(); } [HttpGet] public IActionResult Login() { return View(); } [HttpPost] public async Task<IActionResult> Login(LoginViewModel model) { if (model.Username.Equals("admin")&&model.Password.Equals("123456")) { //名片 List<Claim> claims = new List<Claim> { new Claim(ClaimTypes.Name,model.Username) }; //身份 ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims,"Login")); await HttpContext.Authentication.SignInAsync("Cookie", principal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(30), IsPersistent=false, AllowRefresh=false, }); return RedirectToAction("Index","Account"); } else { return Content("用户名密码错误!"); } } public async Task<IActionResult> Logout() { await HttpContext.Authentication.SignOutAsync("Cookie"); return RedirectToAction("Index", "Home"); }
public class LoginViewModel { [Required] public string Username { get; set; } [Required] public string Password { get; set; } }
@model Practice.WebClient.Models.LoginViewModel @{ ViewData["Title"] = "Login"; } <h2>登录</h2> @using (Html.BeginForm("Login", "Account", new { returnUrl = ViewBag.ReturnUrl }, FormMethod.Post)) { @Html.AntiForgeryToken() <!-- 登录框 --> <div class="loginBox loginAndReg"> <h3>账号登入</h3> <span style="color:red"> @Html.ValidationSummary(true, "")</span> <p class="userName"> <span class="icon"><i></i></span> <label> @Html.TextBoxFor(m => m.Username, new { @placeholder = "请输入登录账号", @class = "changeInput" }) <em class="clean"></em> </label> </p> <p class="userPassword"> <span class="icon"><i></i></span> <label> @Html.PasswordFor(m => m.Password, new { @placeholder = "请输入登录密码", @class = "changeInput" }) <em class="clean"></em> </label> </p> <button type="submit" class="loginBtn" id="inputLogin">登 录</button> </div> }
@{ ViewData["Title"] = "账户中心"; } <h2>账户中心</h2> <h2>Claim:</h2> <dl> @foreach (var claim in User.Claims) { <dt>@claim.Type</dt> <dd>@claim.Value</dd> } </dl>