淺談如何在ASP.NET Core中實(shí)現(xiàn)一個(gè)基礎(chǔ)的身份認(rèn)證
ASP.NET終于可以跨平臺(tái)了,但是不是我們常用的ASP.NET, 而是叫一個(gè)ASP.NET Core的新平臺(tái),他可以跨Windows, Linux, OS X等平臺(tái)來(lái)部署你的web應(yīng)用程序,你可以理解為,這個(gè)框架就是ASP.NET的下一個(gè)版本,相對(duì)于傳統(tǒng)ASP.NET程序,它還是有一些不同的地方的,比如很多類(lèi)庫(kù)在這兩個(gè)平臺(tái)之間是不通用的。
今天首先我們?cè)贏SP.NET Core中來(lái)實(shí)現(xiàn)一個(gè)基礎(chǔ)的身份認(rèn)證,既登陸功能。
前期準(zhǔn)備:
1.推薦使用 VS 2015 Update3 作為你的IDE,下載地址:http://www.dbjr.com.cn/softjc/446184.html
2.你需要安裝.NET Core的運(yùn)行環(huán)境以及開(kāi)發(fā)工具,這里提供VS版:http://www.dbjr.com.cn/softs/472362.html
創(chuàng)建項(xiàng)目:
在VS中新建項(xiàng)目,項(xiàng)目類(lèi)型選擇ASP.NET Core Web Application (.NET Core), 輸入項(xiàng)目名稱為T(mén)estBasicAuthor。
接下來(lái)選擇 Web Application, 右側(cè)身份認(rèn)證選擇:No Authentication
打開(kāi)Startup.cs
在ConfigureServices方法中加入如下代碼:
services.AddAuthorization();
在Configure方法中加入如下代碼:
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie", LoginPath = new PathString("/Account/Login"), AccessDeniedPath = new PathString("/Account/Forbidden"), AutomaticAuthenticate = true, AutomaticChallenge = true });
完整的代碼應(yīng)該是這樣:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddAuthorization(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie", LoginPath = new PathString("/Account/Login"), AccessDeniedPath = new PathString("/Account/Forbidden"), AutomaticAuthenticate = true, AutomaticChallenge = true }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
你或許會(huì)發(fā)現(xiàn)貼進(jìn)去的代碼是報(bào)錯(cuò)的,這是因?yàn)檫€沒(méi)有引入對(duì)應(yīng)的包,進(jìn)入報(bào)錯(cuò)的這一行,點(diǎn)擊燈泡,加載對(duì)應(yīng)的包就可以了。
在項(xiàng)目下創(chuàng)建一個(gè)文件夾命名為Model,并向里面添加一個(gè)類(lèi)User.cs
代碼應(yīng)該是這樣
public class User { public string UserName { get; set; } public string Password { get; set; } }
創(chuàng)建一個(gè)控制器,取名為:AccountController.cs
在類(lèi)中貼入如下代碼:
[HttpGet] public IActionResult Login() { return View(); } [HttpPost] public async Task<IActionResult> Login(User userFromFore) { var userFromStorage = TestUserStorage.UserList .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password); if (userFromStorage != null) { //you can add all of ClaimTypes in this collection var claims = new List<Claim>() { new Claim(ClaimTypes.Name,userFromStorage.UserName) //,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com") }; //init the identity instances var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin")); //signin await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20), IsPersistent = false, AllowRefresh = false }); return RedirectToAction("Index", "Home"); } else { ViewBag.ErrMsg = "UserName or Password is invalid"; return View(); } } public async Task<IActionResult> Logout() { await HttpContext.Authentication.SignOutAsync("Cookie"); return RedirectToAction("Index", "Home"); }
相同的文件里讓我們來(lái)添加一個(gè)模擬用戶存儲(chǔ)的類(lèi)
//for simple, I'm not using the database to store the user data, just using a static class to replace it. public static class TestUserStorage { public static List<User> UserList { get; set; } = new List<User>() { new User { UserName = "User1",Password = "112233"} }; }
接下來(lái)修復(fù)好各種引用錯(cuò)誤。
完整的代碼應(yīng)該是這樣
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using TestBasicAuthor.Model; using System.Security.Claims; using Microsoft.AspNetCore.Http.Authentication; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace TestBasicAuthor.Controllers { public class AccountController : Controller { [HttpGet] public IActionResult Login() { return View(); } [HttpPost] public async Task<IActionResult> Login(User userFromFore) { var userFromStorage = TestUserStorage.UserList .FirstOrDefault(m => m.UserName == userFromFore.UserName && m.Password == userFromFore.Password); if (userFromStorage != null) { //you can add all of ClaimTypes in this collection var claims = new List<Claim>() { new Claim(ClaimTypes.Name,userFromStorage.UserName) //,new Claim(ClaimTypes.Email,"emailaccount@microsoft.com") }; //init the identity instances var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SuperSecureLogin")); //signin await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20), IsPersistent = false, AllowRefresh = false }); return RedirectToAction("Index", "Home"); } else { ViewBag.ErrMsg = "UserName or Password is invalid"; return View(); } } public async Task<IActionResult> Logout() { await HttpContext.Authentication.SignOutAsync("Cookie"); return RedirectToAction("Index", "Home"); } } //for simple, I'm not using the database to store the user data, just using a static class to replace it. public static class TestUserStorage { public static List<User> UserList { get; set; } = new List<User>() { new User { UserName = "User1",Password = "112233"} }; } }
在Views文件夾中創(chuàng)建一個(gè)Account文件夾,在Account文件夾中創(chuàng)建一個(gè)名位index.cshtml的View文件。
貼入如下代碼:
@model TestBasicAuthor.Model.User <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> @using (Html.BeginForm()) { <table> <tr> <td></td> <td>@ViewBag.ErrMsg</td> </tr> <tr> <td>UserName</td> <td>@Html.TextBoxFor(m => m.UserName)</td> </tr> <tr> <td>Password</td> <td>@Html.PasswordFor(m => m.Password)</td> </tr> <tr> <td></td> <td><button>Login</button></td> </tr> </table> } </body> </html>
打開(kāi)HomeController.cs
添加一個(gè)Action, AuthPage.
[Authorize] [HttpGet] public IActionResult AuthPage() { return View(); }
在Views/Home下添加一個(gè)視圖,名為AuthPage.cshtml
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <h1>Auth page</h1> <p>if you are not authorized, you can't visit this page.</p> </body> </html>
到此,一個(gè)基礎(chǔ)的身份認(rèn)證就完成了,核心登陸方法如下:
await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20), IsPersistent = false, AllowRefresh = false });
啟用驗(yàn)證如下:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationScheme = "Cookie", LoginPath = new PathString("/Account/Login"), AccessDeniedPath = new PathString("/Account/Forbidden"), AutomaticAuthenticate = true, AutomaticChallenge = true }); }
在某個(gè)Controller或Action添加[Author],即可配置位需要登陸驗(yàn)證的頁(yè)面。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用.Net Core編寫(xiě)命令行工具(CLI)的方法
這篇文章主要介紹了使用.Net Core編寫(xiě)命令行工具(CLI)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03使用正則Regex來(lái)移除網(wǎng)頁(yè)的EnableViewState實(shí)現(xiàn)思路及代碼
創(chuàng)建好網(wǎng)頁(yè)時(shí),什么都沒(méi)有寫(xiě),但運(yùn)行時(shí)會(huì)發(fā)現(xiàn)源程序(View Source),下面一段,此刻,也許你會(huì)想起,在網(wǎng)頁(yè)有一個(gè)屬性EnableViewState,在某些時(shí)候我們并不需要它,接下來(lái)將介紹如何移除它,感興趣的朋友可以了解下啊2013-01-01asp.net實(shí)現(xiàn)服務(wù)器文件下載到本地的方法
這篇文章主要介紹了asp.net實(shí)現(xiàn)服務(wù)器文件下載到本地的方法,需要的朋友可以參考下2017-02-02.net出現(xiàn)80080005錯(cuò)誤的解決辦法分享
這篇文章介紹了.net出現(xiàn)80080005錯(cuò)誤的解決辦法,有需要的朋友可以參考一下,希望可以對(duì)你有所幫助2013-07-07在FireFox/IE下Response中文文件名亂碼問(wèn)題解決方案
只是針對(duì)沒(méi)有空格和IE的情況下使用Response.AppendHeader()如果想在FireFox下輸出沒(méi)有編碼的文件,并且IE下輸出的文件名中空格不為+號(hào),就要多一次判斷了,接下來(lái)將詳細(xì)介紹下感興趣的朋友可以了解下,或許對(duì)你有所幫助2013-02-02ASP.NET Mvc開(kāi)發(fā)之刪除修改數(shù)據(jù)
這篇文章主要介紹了ASP.NET Mvc開(kāi)發(fā)中的刪除修改數(shù)據(jù)功能,感興趣的小伙伴們可以參考一下2016-03-03Asp.net core利用dynamic簡(jiǎn)化數(shù)據(jù)庫(kù)訪問(wèn)
這篇文章介紹了Asp.net core利用dynamic簡(jiǎn)化數(shù)據(jù)庫(kù)訪問(wèn)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07