Implementation of Authentication and Privilege Management Based on mvc5+ef6+Bootstrap Framework

  • 2021-10-24 23:32:22
  • OfStack

Recently, I completed a large single subarchitecture with my friends, which is mvc5+ef6+Bootstrap, using vs2015 and the database is sql server2014. Friends to do the structure, after the completion of the project feel a lot worth learning, here to sum up the following 1 experience.

Create Project 1 and start deleting the files IdentityConfig. cs and Startup. Auth. cs in the App_Start directory; Empty the Modle folder, Controller folder and the corresponding View; Delete the files ApplicationInsights. config and Startup. cs in the directory

Modify the web. config file (add < add key="owin:AutomaticAppStartup" value="false"/ > Do not use the Startup. cs file to start the project)


<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"/> <!-- Remove the at the beginning of creating the project Startup.cs Settings of files -->
</appSettings>

(Don't use them because they are too redundant.)

Get rid of redundant content officially started, first introduce the database this block, database we are configured can be manually generated and modified

1. In the project directory, you want to create the Migrations folder and add the Configuration. cs file


internal sealed class Configuration : DbMigrationsConfiguration<AccountContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "UserProject.DAL.AccountContext";
}
protected override void Seed(AccountContext context)
{
//base.Seed(context);
}
}

Add the AccountContext. cs file under the Modle folder


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>

Then use the tools in vs 2015-NuGet Package Manager-Package Management Control Platform

Enter add-migration Initial and press Enter when entering update-database. You will see the AccountContext database under the App_Data folder.

2. Add the User. css file under the Modle folder


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// Role enumeration 
{  Administrator  = 0,  Employees  = 1,  Manager  = 2,  General Manager  = 3,  Chairman of the Board  = 4 }

Add the Account. cs file in the ViewModle folder


public class Account
{
[Required]
public string Name { get; set; }
[Required]
public string Password { get; set; }
public string RePassword { get; set; }
}

It is recommended that Controller after creating BaseController inherit it and use it


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);// Here, in order not to access the user table every time, you can do 1 Static class, which stores user table information .
_userInfo = user == null ? null : new User()
{
ID = user.ID,
UserName = user.UserName,
Role = user.Role
};
}
return _userInfo;
}
}
      // Validation role: Get Action Adj. CustomAttributes Filter roles 
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", " You do not have permission to access this feature !");
}
}
// Here is the note log Use 
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
var msg = $" Users : {CurrentUserInfo?.UserName},  Link : {Request.Url}";
if (Request.HttpMethod == "POST")
msg += $",  Data : {HttpUtility.UrlDecode(Request.Form.ToString())}";
//Log.Debug(msg);
}
}

AdminController inherits BaseController


[Authorize]
public ActionResult Index()
{
return View(db.Users.ToList());
}
[Authorize, AuthorizeRole(Role. Administrator )]
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);
}

Login page:


@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=" Login " class="btn btn-primary" />
</div>
</div>
}

Login 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);// Put the user name into the Cookie Medium 
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("Name", " User name does not exist !");
}
}
return View(model);
}
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}

The Details must be accessed in the administrator role when accessing the Action as described above.


Related articles: