基於mvc5+ef6+Bootstrap框架完成身份驗證和權限治理。本站提示廣大學習愛好者:(基於mvc5+ef6+Bootstrap框架完成身份驗證和權限治理)文章只能為提供參考,不一定能成為您想要的結果。以下是基於mvc5+ef6+Bootstrap框架完成身份驗證和權限治理正文
近和同伙完成了一個年夜票據架構是mvc5+ef6+Bootstrap,用的是vs2015,數據庫是sql server2014。同伙做的架構,項目完成後認為許多值得我進修,在這裡總結下一些心得。
創立項目一開端刪失落App_Start目次下的IdentityConfig.cs和Startup.Auth.cs文件;清空Modle文件夾,Controller文件夾和響應的View; 刪除目次下的ApplicationInsights.config文件和Startup.cs文件
修正web.config文件(添加<add key="owin:AutomaticAppStartup" value="false"/>不應用Startup.cs文件來啟動項目)
<appSettings> <add key="webpages:Version" value="3.0.0.0" /> <add key="webpages:Enabled" value="false" /> <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> <add key="owin:AutomaticAppStartup" value="false"/> <!--去失落創立項目初的Startup.cs文件的設置--> </appSettings>
(不消他們是由於自帶的這些內容太冗余)
去失落冗余內容正式開端,起首引見數據庫這一塊,數據庫我們是設置裝備擺設的可以手動生成和修正的
1.在項目目次想創立Migrations文件夾,外面添加Configuration.cs文件
internal sealed class Configuration : DbMigrationsConfiguration<AccountContext> { public Configuration() { AutomaticMigrationsEnabled = true; ContextKey = "UserProject.DAL.AccountContext"; } protected override void Seed(AccountContext context) { //base.Seed(context); } }
在Modle文件夾下添加AccountContext.cs文件
public class AccountContext:DbContext { public AccountContext():base("AccountContext") { } public DbSet<User> Users { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } <connectionStrings> <add name="AccountContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UserProject.mdf;Initial Catalog=UserProject;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings>
然後 應用vs2015外面的對象-NuGet擔保理器-法式擔保理掌握平台
輸出add-migration Initial 按回車,在輸出update-database按回車。在App_Data文件夾下就會看到AccountContext數據庫了。
2.在Modle文件夾下添加User.css文件
public class User { public int ID { get; set; } public string UserName { get; set; } public string Password { get; set; } public Role Role { get; set; } } public enum Role//腳色列舉 { 治理員 = 0, 員工 = 1, 司理 = 2, 總司理 = 3, 董事長 = 4 }
在ViewModle文件夾中添加Account.cs文件
public class Account { [Required] public string Name { get; set; } [Required] public string Password { get; set; } public string RePassword { get; set; } }
這裡推舉創立BaseController以後的Controller就繼續它來應用
public class BaseController : Controller { public string UserName => User.Identity.Name; public AccountContext db = new AccountContext(); private User _userInfo = null; public User CurrentUserInfo { get { if (_userInfo == null) { var user = db.Users.SingleOrDefault(u => u.UserName == UserName);//此處為了不每次拜訪用戶表可以做一個靜態類,外面寄存用戶表信息. _userInfo = user == null ? null : new User() { ID = user.ID, UserName = user.UserName, Role = user.Role }; } return _userInfo; } } //驗證腳色:獲得Action的CustomAttributes,過濾腳色 protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); var authRoleAtt = filterContext.ActionDescriptor.GetCustomAttributes(false).SingleOrDefault(att => att is AuthorizeRoleAttribute) as AuthorizeRoleAttribute; if (authRoleAtt == null && CurrentUserInfo != null) return; if (!authRoleAtt.Roles.Contains(CurrentUserInfo.Role)) { filterContext.Result = View("NoPermission", "_Layout", "您沒有權限拜訪此功效!"); } } //這裡是記log用 protected override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); var msg = $"用戶: {CurrentUserInfo?.UserName}, 鏈接: {Request.Url}"; if (Request.HttpMethod == "POST") msg += $", 數據: {HttpUtility.UrlDecode(Request.Form.ToString())}"; //Log.Debug(msg); } }
AdminController繼續BaseController
[Authorize] public ActionResult Index() { return View(db.Users.ToList()); } [Authorize, AuthorizeRole(Role.治理員)] public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } User user = db.Users.Find(id); if (user == null) { return HttpNotFound(); } return View(user); }
登錄頁面:
@model UserProject.ViewModels.Account @{ ViewBag.Title = "Login"; } @using (Html.BeginForm("Login", "Admin",FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBoxFor(m => m.Name, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.PasswordFor(m => m.Password, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="登錄" class="btn btn-primary" /> </div> </div> }
登錄的Action:
[AllowAnonymous] public ActionResult Login() { return View(); } [HttpPost, AllowAnonymous] public ActionResult Login(Account model) { if (ModelState.IsValid) { var user = db.Users.SingleOrDefault(t => t.UserName == model.Name && t.Password == model.Password); if (user != null) { FormsAuthentication.SetAuthCookie(model.Name, false);//將用戶名放入Cookie中 return RedirectToAction("Index"); } else { ModelState.AddModelError("Name", "用戶名不存在!"); } } return View(model); } public ActionResult LogOff() { FormsAuthentication.SignOut(); return RedirectToAction("Login"); }
依照以上方法 拜訪Details這個Action的時刻必需是治理員腳色。
以上所述是小編給年夜家引見的基於mvc5+ef6+Bootstrap框架完成身份驗證和權限治理,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!