標籤:string value ica 加密 username generate editor net tick
---恢複內容開始---
asp.net mvc5 登陸及使用者身份管理(基礎)
近期再寫asp.net的網站其中有部分網頁需要擁有特權的人才能訪問(admin),所以研究如何可以實現使用者身份管理。
因為我一開始建立的項目是一個空項目,添加檔案夾及核心引用勾選的是mvc所以出現了不能使用Authorize特性登陸;
於是建立了一個項目並且選擇了身分識別驗證為個人使用者賬戶。對比發現可能是因為少了startup.auth.cs檔案所致。
下面這段代碼是我寫的登陸代碼
1 [HttpGet] 2 public ActionResult login() 3 { 4 return View(); 5 } 6 [HttpPost] 7 [ValidateAntiForgeryToken] 8 public ActionResult login(Login login) 9 {10 var users = db.Users.Where(a => a.Name == login.UserName);11 if (!users.Any())12 return View();13 User user = users.First();14 var cards = db.Cards.Where(a => a.User_id == user.Id);15 Card card = cards.First();16 if(login.Password=="123"&&card.Privilege==2)17 {18 FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(19 1,20 login.UserName,21 DateTime.Now,22 DateTime.Now.AddMinutes(20),23 false,24 "admin"25 );26 var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(Ticket));27 cookie.HttpOnly = true;28 HttpContext.Response.Cookies.Add(cookie);29 return RedirectToAction("../DataBase/SelectUser");30 }31 return RedirectToAction("login");32 33 }
其中FormsAuthenticationTicket為加密票據,用於存放使用者的資訊,其中“admin”為使用者的許可權,用於之後控制器中Authorize(Roles="admin")特徵。
接下來是要限制許可權的控制器
1 public class DataBaseController : Controller 2 { 3 4 private AccessControlContext db = new AccessControlContext(); 5 //Users 6 public ActionResult SelectUser() 7 { 8 var user = db.Users; 9 return View(user.ToList());10 }11 [HttpGet]12 [Authorize(Roles = "admin")]13 public ActionResult InsertUser()14 {15 return View();16 }17 }
其中標有[Authorize(Roles="admin"]標誌的就是只有擁有admin許可權的使用者才能使用。當然也可以將AuthorizeAttribute註冊為全域過濾器,需要把它添加到RegisterGlobalFilters(包含在\App_Start\FilterConfig.cs檔案中)
public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new System.Web.Mvc.AuthorizeAttribute()); }
然後在需要外部存取的方法前面用[AllowAnonymous]特性裝飾即可。
如果使用者身分識別驗證失敗,一般我們會選擇將使用者重新導向到登陸介面。以便對有權查看原來頁面的使用者進行身分識別驗證。
在asp.net以前的版本,這個重新導向被FormsAuthenticationModule的OnLeave方法截獲,並轉而重新導向到在應用程式web.config檔案中定義的登陸頁面,代碼如下
1 <authentication mode="Forms">2 <forms loginUrl="~/Account/Login" timeout="2880" />3 </authentication>
但是在mvc5中我們可以直接更改Stratup.auth.cs中的代碼
app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // 當使用者登入時使應用程式可以驗證安全戳。 // 這是一項安全功能,當你更改密碼或者向帳戶添加外部登入名稱時,將使用此功能。 OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } });
上面這段代碼中LoginPath這個變數就是指向我們的登陸頁面,我們可以更改後面的“/Account/Login”來更改指向。Startup.Auth.cs檔案我也不是很清楚,後續我應該還會針對此檔案來更新文章。
然後是登陸view的代碼
1 @model Access_Control_System.Models.Login 2 @{ 3 ViewBag.Title = "View"; 4 } 5 6 <h2>Login</h2> 7 8 @using (Html.BeginForm()) 9 {10 @Html.AntiForgeryToken();11 @Html.ValidationSummary(true,"",new { @class="text-danger"})12 <fieldset class="form-horizontal">13 <div class="form-group">14 @Html.LabelFor(model=>model.UserName,htmlAttributes:new {@class="control-label col-md-2"})15 <div class="col-md-10">16 @Html.EditorFor(model=>model.UserName,new { htmlAttributes=new { @class="form-control"} })17 @Html.ValidationMessageFor(model=>model.UserName,"",new {@class="text-danger"})18 </div>19 </div>20 <div class="form-group">21 @Html.LabelFor(model=>model.Password, htmlAttributes: new { @class = "control-label col-md-2" })22 <div class="col-md-10">23 @Html.EditorFor(model=>model.Password,new { htmlAttributes=new { @class="form-control"} })24 @Html.ValidationMessageFor(model=>model.UserName,"",new { @class="text-danger"})25 </div>26 </div>27 28 29 <div class="form-group">30 <div class="col-md-offset-2 col-md-10">31 <input type="submit" value="Submit" class="btn btn-default" />32 </div>33 </div>34 35 </fieldset>36 37 }
asp.net mvc 登陸實現