您好,登錄后才能下訂單哦!
怎么在ASP.NET Core中實現一個身份認證功能?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
創建項目:
在VS中新建項目,項目類型選擇ASP.NET Core Web Application (.NET Core), 輸入項目名稱為TestBasicAuthor。
接下來選擇 Web Application, 右側身份認證選擇:No Authentication
打開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 });
完整的代碼應該是這樣:
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?}"); }); }
你或許會發現貼進去的代碼是報錯的,這是因為還沒有引入對應的包,進入報錯的這一行,點擊燈泡,加載對應的包就可以了。
在項目下創建一個文件夾命名為Model,并向里面添加一個類User.cs
代碼應該是這樣
public class User { public string UserName { get; set; } public string Password { get; set; } }
創建一個控制器,取名為:AccountController.cs
在類中貼入如下代碼:
[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"} }; }
接下來修復好各種引用錯誤。
完整的代碼應該是這樣
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文件夾中創建一個Account文件夾,在Account文件夾中創建一個名位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>
打開HomeController.cs
添加一個Action, AuthPage.
[Authorize] [HttpGet] public IActionResult AuthPage() { return View(); }
在Views/Home下添加一個視圖,名為AuthPage.cshtml
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <h2>Auth page</h2> <p>if you are not authorized, you can't visit this page.</p> </body> </html>
到此,一個基礎的身份認證就完成了,核心登陸方法如下:
await HttpContext.Authentication.SignInAsync("Cookie", userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(20), IsPersistent = false, AllowRefresh = false });
啟用驗證如下:
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 }); }
關于怎么在ASP.NET Core中實現一個身份認證功能問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。