- 浏览: 2162375 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (1878)
- [网站分类]ASP.NET (141)
- [网站分类]C# (80)
- [随笔分类]NET知识库 (80)
- [随笔分类]摘抄文字[非技术] (3)
- [随笔分类]养生保健 (4)
- [网站分类]读书区 (16)
- [随笔分类]赚钱 (7)
- [网站分类].NET新手区 (233)
- [随笔分类]网站 (75)
- [网站分类]企业信息化其他 (4)
- [网站分类]首页候选区 (34)
- [网站分类]转载区 (12)
- [网站分类]SQL Server (16)
- [网站分类]程序人生 (7)
- [网站分类]WinForm (2)
- [随笔分类]错误集 (12)
- [网站分类]JavaScript (3)
- [随笔分类]小说九鼎记 (69)
- [随笔分类]技术文章 (15)
- [网站分类]求职面试 (3)
- [网站分类]其他技术区 (6)
- [网站分类]非技术区 (10)
- [发布至博客园首页] (5)
- [网站分类]jQuery (6)
- [网站分类].NET精华区 (6)
- [网站分类]Html/Css (10)
- [随笔分类]加速及SEO (10)
- [网站分类]Google开发 (4)
- [随笔分类]旅游备注 (2)
- [网站分类]架构设计 (3)
- [网站分类]Linux (23)
- [随笔分类]重要注册 (3)
- [随笔分类]Linux+PHP (10)
- [网站分类]PHP (11)
- [网站分类]VS2010 (2)
- [网站分类]CLR (1)
- [网站分类]C++ (1)
- [网站分类]ASP.NET MVC (2)
- [网站分类]项目与团队管理 (1)
- [随笔分类]个人总结 (1)
- [随笔分类]问题集 (3)
- [网站分类]代码与软件发布 (1)
- [网站分类]Android开发 (1)
- [网站分类]MySQL (1)
- [网站分类]开源研究 (6)
- ddd (0)
- 好久没写blog了 (0)
- sqlserver (2)
最新评论
-
JamesLiuX:
博主,能组个队么,我是Freelancer新手。
Freelancer.com(原GAF – GetAFreelancer)帐户里的钱如何取出? -
yw10260609:
我认为在混淆前,最好把相关代码备份一下比较好,不然项目完成后, ...
DotFuscator 小记 -
日月葬花魂:
大哥 能 加我个QQ 交流一下嘛 ?51264722 我Q ...
web应用程序和Web网站区别 -
iaimg:
我想问下嵌入delphi写的程序总是出现窗体后面感觉有个主窗体 ...
C#自定义控件:WinForm将其它应用程序窗体嵌入自己内部 -
iaimg:
代码地址下不了啊!
C#自定义控件:WinForm将其它应用程序窗体嵌入自己内部
mvc中有关用户权限的详解
ASP.NET provides IPrincipal and IIdentity interfaces to represents the identity and role for a user. You can create a custom solution by evaluating the IPrincipal and IIdentity interfaces which are bound to the HttpContext as well as the current thread.
- public class CustomPrincipal : IPrincipal
- {
- public IIdentity Identity { get; private set; }
- public bool IsInRole(string role)
- {
- if (roles.Any(r => role.Contains(r)))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- public CustomPrincipal(string Username)
- {
- this.Identity = new GenericIdentity(Username);
- }
- public int UserId { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string[] roles { get; set; }
- }
Now you can put this CustomPrincipal objects into the thread’s currentPrinciple property and into the HttpContext’s User property to accomplish your custom authentication and authorization process.
ASP.NET Forms Authentication
ASP.NET forms authentication occurs after IIS authentication is completed. You can configure forms authentication by using forms element with in web.config file of your application. The default attribute values for forms authentication are shown below:
- <system.web>
- <authentication mode="Forms">
- <forms loginUrl="Login.aspx"
- protection="All"
- timeout="30"
- name=".ASPXAUTH"
- path="/"
- requireSSL="false"
- slidingExpiration="true"
- defaultUrl="default.aspx"
- cookieless="UseDeviceProfile"
- enableCrossAppRedirects="false" />
- </authentication>
- </system.web>
The FormsAuthentication class creates the authentication cookie automatically when SetAuthCookie() or RedirectFromLoginPage() methods are called. The value of authentication cookie contains a string representation of the encrypted and signed FormsAuthenticationTicket object.
You can create the FormsAuthenticationTicket object by specifying the cookie name, version of the cookie, directory path, issue date of the cookie, expiration date of the cookie, whether the cookie should be persisted, and optionally user-defined data as shown below:
- FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
- "userName",
- DateTime.Now,
- DateTime.Now.AddMinutes(30), // value of time out property
- false, // Value of IsPersistent property
- String.Empty,
- FormsAuthentication.FormsCookiePath);
Now, you can encrypt this ticket by using the Encrypt method FormsAuthentication class as given below:
- string encryptedTicket = FormsAuthentication.Encrypt(ticket);
Note
To encrypt FormsAuthenticationTicket ticket set the protection attribute of the forms element to All or Encryption.
Custom Authorization
ASP.NET MVC provides Authorization filter to authorize a user. This filter can be applied to an action, a controller, or even globally. This filter is based on AuthorizeAttribute class. You can customize this filter by overriding OnAuthorization() method as shown below:
- public class CustomAuthorizeAttribute : AuthorizeAttribute
- {
- public string UsersConfigKey { get; set; }
- public string RolesConfigKey { get; set; }
- protected virtual CustomPrincipal CurrentUser
- {
- get { return HttpContext.Current.User as CustomPrincipal; }
- }
- public override void OnAuthorization(AuthorizationContext filterContext)
- {
- if (filterContext.HttpContext.Request.IsAuthenticated)
- {
- var authorizedUsers = ConfigurationManager.AppSettings[UsersConfigKey];
- var authorizedRoles = ConfigurationManager.AppSettings[RolesConfigKey];
- Users = String.IsNullOrEmpty(Users) ? authorizedUsers : Users;
- Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;
- if (!String.IsNullOrEmpty(Roles))
- {
- if (!CurrentUser.IsInRole(Roles))
- {
- filterContext.Result = new RedirectToRouteResult(new
- RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
- // base.OnAuthorization(filterContext); //returns to login url
- }
- }
- if (!String.IsNullOrEmpty(Users))
- {
- if (!Users.Contains(CurrentUser.UserId.ToString()))
- {
- filterContext.Result = new RedirectToRouteResult(new
- RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));
- // base.OnAuthorization(filterContext); //returns to login url
- }
- }
- }
- }
- }
User Authentication
A user will be authenticated if IsAuthenticated property returns true. For authenticating a user you can use one of the following two ways:
-
Thread.CurrentPrincipal.Identity.IsAuthenticated
-
HttpContext.Current.User.Identity.IsAuthenticated
Designing Data Model
Now it’s time to create data access model classes for creating and accessing Users and Roles as shown below:
- public class User
- {
- public int UserId { get; set; }
- [Required]
- public String Username { get; set; }
- [Required]
- public String Email { get; set; }
- [Required]
- public String Password { get; set; }
- public String FirstName { get; set; }
- public String LastName { get; set; }
- public Boolean IsActive { get; set; }
- public DateTime CreateDate { get; set; }
- public virtual ICollection<Role> Roles { get; set; }
- }
- public class Role
- {
- public int RoleId { get; set; }
- [Required]
- public string RoleName { get; set; }
- public string Description { get; set; }
- public virtual ICollection<User> Users { get; set; }
- }
Defining Database Context with code first mapping between User and Role
Using Entity Framework code first approach, create a DataContext having User and Role entities with its relational mapping details as shown below:
- public class DataContext : DbContext
- {
- public DataContext()
- : base("DefaultConnection")
- {
- }
- protected override void OnModelCreating(DbModelBuilder modelBuilder)
- {
- modelBuilder.Entity<User>()
- .HasMany(u => u.Roles)
- .WithMany(r=>r.Users)
- .Map(m =>
- {
- m.ToTable("UserRoles");
- m.MapLeftKey("UserId");
- m.MapRightKey("RoleId");
- });
- }
- public DbSet<User> Users { get; set; }
- public DbSet<Role> Roles { get; set; }
- }
Code First Database Migrations
With the help of entity framework code first database migrations create the database named as Security in the SQL Server. Run the following command through Visual Studio Package Manager Console to migrate your code into SQL Server database.
After running first command i.e. enabling migrations for your project, add seed data to Configuration.cs file of Migrations folder as shown below:
- protected override void Seed(Security.DAL.DataContext context)
- {
- Role role1 = new Role { RoleName = "Admin" };
- Role role2 = new Role { RoleName = "User" };
- User user1 = new User { Username = "admin", Email = "admin@ymail.com", FirstName = "Admin", Password = "123456", IsActive = true, CreateDate = DateTime.UtcNow, Roles = new List<role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">()</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">};</span></role>
- <role style="BOX-SIZING: border-box"></role>
- <role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">User</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> user2 </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,0,128); VERTICAL-ALIGN: top" class="kwd">new</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">User</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">{</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Username</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,104,32); VERTICAL-ALIGN: top" class="str">"user1"</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Email</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,104,32); VERTICAL-ALIGN: top" class="str">"user1@ymail.com"</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">FirstName</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,104,32); VERTICAL-ALIGN: top" class="str">"User1"</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Password</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,104,32); VERTICAL-ALIGN: top" class="str">"123456"</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">IsActive</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,0,128); VERTICAL-ALIGN: top" class="kwd">true</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">CreateDate</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">DateTime</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">UtcNow</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">,</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Roles</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">=</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(255,0,128); VERTICAL-ALIGN: top" class="kwd">new</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">List</span><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">()</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">};</span></role></role>
- <role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"></role></role>
- <role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> user1</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Roles</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Add</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">(</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln">role1</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">);</span></role></role>
- <role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> user2</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Roles</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Add</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">(</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln">role2</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">);</span></role></role>
- <role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"></role></role>
- <role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> context</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Users</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Add</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">(</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln">user1</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">);</span></role></role>
- <role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> context</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Users</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">.</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(83,83,166); VERTICAL-ALIGN: top" class="typ">Add</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">(</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln">user2</span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">);</span></role></role>
- <role style="BOX-SIZING: border-box"><role style="BOX-SIZING: border-box"><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pln"> </span><span style="BOX-SIZING: border-box; MARGIN: 0px; COLOR: rgb(57,49,36); VERTICAL-ALIGN: top" class="pun">}</span></role></role>
When above three commands will be executed successfully as shown above, the following database will be created in your SQL Server.
Solution Structure
Designing View Model
Create a view model class for handing login process as given below:
- public class LoginViewModel
- {
- [Required]
- [Display(Name = "User name")]
- public string Username { get; set; }
- [Required]
- [DataType(DataType.Password)]
- [Display(Name = "Password")]
- public string Password { get; set; }
- [Display(Name = "Remember me?")]
- public bool RememberMe { get; set; }
- }
- public class CustomPrincipalSerializeModel
- {
- public int UserId { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string[] roles { get; set; }
- }
Forms Authentication Initialization
- public class AccountController : Controller
- {
- DataContext Context = new DataContext();
- //
- // GET: /Account/
- public ActionResult Index()
- {
- return View();
- }
- [HttpPost]
- public ActionResult Index(LoginViewModel model, string returnUrl = "")
- {
- if (ModelState.IsValid)
- {
- var user = Context.Users.Where(u => u.Username == model.Username && u.Password == model.Password).FirstOrDefault();
- if (user != null)
- {
- var roles=user.Roles.Select(m => m.RoleName).ToArray();
- CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
- serializeModel.UserId = user.UserId;
- serializeModel.FirstName = user.FirstName;
- serializeModel.LastName = user.LastName;
- serializeModel.roles = roles;
- string userData = JsonConvert.SerializeObject(serializeModel);
- FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
- 1,
- user.Email,
- DateTime.Now,
- DateTime.Now.AddMinutes(15),
- false,
- userData);
- string encTicket = FormsAuthentication.Encrypt(authTicket);
- HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
- Response.Cookies.Add(faCookie);
- if(roles.Contains("Admin"))
- {
- return RedirectToAction("Index", "Admin");
- }
- else if (roles.Contains("User"))
- {
- return RedirectToAction("Index", "User");
- }
- else
- {
- return RedirectToAction("Index", "Home");
- }
- }
- ModelState.AddModelError("", "Incorrect username and/or password");
- }
- return View(model);
- }
- [AllowAnonymous]
- public ActionResult LogOut()
- {
- FormsAuthentication.SignOut();
- return RedirectToAction("Login", "Account", null);
- }
- }
- public class MvcApplication : System.Web.HttpApplication
- {
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- WebApiConfig.Register(GlobalConfiguration.Configuration);
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
- Database.SetInitializer<DataContext>(new DataContextInitilizer());
- }
- protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
- {
- HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
- if (authCookie != null)
- {
- FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
- CustomPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject<CustomPrincipalSerializeModel>(authTicket.UserData);
- CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
- newUser.UserId = serializeModel.UserId;
- newUser.FirstName = serializeModel.FirstName;
- newUser.LastName = serializeModel.LastName;
- newUser.roles = serializeModel.roles;
- HttpContext.Current.User = newUser;
- }
- }
- }
Base Controller for accessing Current User
Create a base controller for accessing your User data in your all controller. Inherit, your all controller from this base controller to access user information from the UserContext.
- public class BaseController : Controller
- {
- protected virtual new CustomPrincipal User
- {
- get { return HttpContext.User as CustomPrincipal; }
- }
- }
- public class HomeController : BaseController
- {
- //
- // GET: /Home/
- public ActionResult Index()
- {
- string FullName = User.FirstName + " " + User.LastName;
- return View();
- }
- }
Base View Page for accessing Current User
Create a base class for all your views for accessing your User data in your all views as shown below:
- public abstract class BaseViewPage : WebViewPage
- {
- public virtual new CustomPrincipal User
- {
- get { return base.User as CustomPrincipal; }
- }
- }
- public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
- {
- public virtual new CustomPrincipal User
- {
- get { return base.User as CustomPrincipal; }
- }
- }
Register this class with in the \Views\Web.config as base class for all your views as given below:
- <system.web.webPages.razor>
- <!--Other code has been removed for clarity-->
- <pages pageBaseType="Security.DAL.Security.BaseViewPage">
- <namespaces>
- <!--Other code has been removed for clarity-->
- </namespaces>
- </pages>
- </system.web.webPages.razor>
Now you can access the authenticated user information on all your view in easy and simple way as shown below in Admin View:
- @{
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_AdminLayout.cshtml";
- }
- <h4>Welcome : @User.FirstName</h4>
- <h1>Admin DashBoard</h1>
Login View
- @model Security.Models.LoginViewModel
- @{
- ViewBag.Title = "Index";
- }
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <div class="form-horizontal">
- <h4>User Login</h4>
- <hr />
- @Html.ValidationSummary(true)
- <div class="form-group">
- @Html.LabelFor(model => model.Username, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Username)
- @Html.ValidationMessageFor(model => model.Username)
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Password)
- @Html.ValidationMessageFor(model => model.Password)
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.RememberMe, new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.RememberMe)
- @Html.ValidationMessageFor(model => model.RememberMe)
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Login" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
Applying CustomAuthorize attribute
To make secure your admin or user pages, decorate your Admin and User controllers with CustomAuthorize attribute as defined above and specify the uses or roles to access admin and user pages.
- [CustomAuthorize(Roles= "Admin")]
- // [CustomAuthorize(Users = "1")]
- public class AdminController : BaseController
- {
- //
- // GET: /Admin/
- public ActionResult Index()
- {
- return View();
- }
- }
- [CustomAuthorize(Roles= "User")]
- // [CustomAuthorize(Users = "1,2")]
- public class UserController : BaseController
- {
- //
- // GET: /User/
- public ActionResult Index()
- {
- return View();
- }
- }
You can also specify the Roles and Users with in your web.config as a key to avoid hard code values for Users and Roles at the controller level.
- <add key="RolesConfigKey" value="Admin"/>
- <add key="UsersConfigKey" value="2,3"/>
Use one of these keys within the CustomAuthorize attribute as shown below:
- //[CustomAuthorize(RolesConfigKey = "RolesConfigKey")]
- [CustomAuthorize(UsersConfigKey = "UsersConfigKey")]
- public class AdminController : BaseController
- {
- //
- // GET: /Admin/
- public ActionResult Index()
- {
- return View();
- }
- }
- [CustomAuthorize(RolesConfigKey = "RolesConfigKey")]
- // [CustomAuthorize(UsersConfigKey = "UsersConfigKey")]
- public class UserController : BaseController
- {
- //
- // GET: /User/
- public ActionResult Index()
- {
- return View();
- }
- }
Test your application
When you will run your application and will login into the application using user1, you will be redirected to User dashboard as shown below:
When user will try to access unauthorized pages such as Admin dashboard using URL: http://localhost:11681/Admin , he will get the custom error page as shown below:
相关推荐
**MVC权限系统详解** 在IT行业中,MVC(Model-View-Controller)架构模式被广泛应用于Web应用程序的开发,因为它能有效地分离业务逻辑、数据处理和用户界面。本项目是一个基于MVC模式构建的权限管理系统,它包含了...
### MVC权限控制案例详解 #### 一、背景与目的 在现代Web开发中,权限管理是确保应用程序安全性和用户访问合理性的关键环节之一。对于基于ASP.NET MVC框架的应用程序而言,设计合理的权限控制系统尤为重要。本文将...
**MVC4通用权限管理源码详解** 在Web开发领域,Microsoft的ASP.NET MVC框架以其灵活性、可测试性和模块化设计而备受青睐。MVC4是该框架的一个版本,它在MVC3的基础上进行了优化和增强,引入了新的功能和性能改进。...
**MVC模式详解** MVC(Model-View-Controller)是一种广泛应用于Web应用程序设计的软件架构模式,旨在提高代码的可维护性和可扩展性。在MVC模式中,应用程序的逻辑被分成了三个主要组件:模型(Model)、视图(View...
例如,管理员、普通用户等。系统可能包含角色注册、角色分配、角色权限设置等功能。 5. 权限控制:权限控制是系统安全的核心,通过授权确定用户对资源的访问权限。ASP.NET MVC可以结合授权过滤器实现这一功能,比如...
**ASP.NET + Web + MVC4.0 + EasyUI 权限管理系统详解** 本文将深入探讨如何使用ASP.NET、Web技术和MVC4.0框架,结合EasyUI库来构建一个先进的权限管理系统。首先,我们需要理解ASP.NET是微软推出的一种用于构建...
在权限管理系统中,我们可以利用EasyUI的这些组件创建直观的用户界面,如用户管理界面、角色分配面板、权限设置表单等。 在权限管理中,常见的功能包括用户注册与登录、角色管理、权限分配和访问控制。用户注册与...
### Spring MVC核心组件之HandlerMapping详解 #### 一、引言 在Java Web开发领域,Spring MVC框架因其灵活且强大的特性而备受青睐。它提供了一种简洁的方式来构建可维护、可扩展的应用程序。Spring MVC的核心组件之...
- **角色分配(Role Assignment)**:管理员可以将角色分配给用户,赋予其角色所包含的所有权限。 - **权限分配(Permission Assignment)**:除了角色分配,也可以直接给用户分配特定的权限。 **4. MVC4的实现...
在AngelRM_MVC中,模型层可能包括用户管理、角色管理、权限管理等实体类,用于处理与数据库的交互,如增删改查操作。 2. 视图(View):是用户看到和与之交互的界面。在系统中,视图可能包括各种网页或组件,如登录...
Spring MVC 是一个强大的Java Web应用程序框架,用于构建高效、模块化的Web应用。...在实际开发中,还可以集成其他Spring模块,如Spring Security进行权限管理,Spring Data进行数据访问,进一步提升应用的功能和性能。
如果出现安装问题,可以尝试以管理员权限运行安装程序。 **5. 中文支持** MVC3中文安装包的主要目的是提供用户界面的中文本地化,包括错误消息、帮助文档和开发环境的界面。这使得中国开发者和用户能够更直观地理解...
#### 六、Spring MVC 配置文件详解 Spring MVC 的配置文件通常包含了以下几个关键部分: 1. **DispatcherServlet 配置**:配置 DispatcherServlet 如何初始化以及加载配置文件。 2. **视图解析器配置**:配置 ...
Spring MVC支持根据用户的locale设置提供不同的资源和服务,通过`LocaleResolver`和`MessageSource`实现。 8. **RESTful风格** Spring MVC支持创建RESTful服务,通过`@GetMapping`、`@PostMapping`等注解映射HTTP...
1. **用户管理**:创建、编辑、删除用户,分配角色。 2. **角色管理**:定义角色,分配权限。 3. **权限分配**:将特定操作或资源授权给角色,角色再授予给用户。 4. **认证与授权**:通过MVC的授权特性,控制用户...
Struts 2 是一个强大的Java Web应用程序框架,它基于Model-View-Controller(MVC)设计模式,提供了灵活的架构来构建可维护性和扩展性良好的Web应用。在深入讲解Struts 2之前,我们先来了解一下MVC模式的基本概念。 ...
在"权限管理、日志管理、用户管理、角色管理、菜单管理"这些场景中,模型会包含各种实体类,如User、Role、Menu等,以及相应的业务逻辑方法,如用户的登录验证、角色权限的分配等。 2. **视图(View)**:视图是...
在这个基于Java MVC的管理员管理系统中,我们可以看到它主要关注的是后端开发,特别是针对管理者的功能实现。 1. **MVC模式详解**: - **Model(模型)**:负责处理业务逻辑和数据管理,通常与数据库交互,获取或...
**MVC新闻管理系统详解** MVC(Model-View-Controller)模式是一种软件设计模式,广泛应用于Web应用开发中,尤其在PHP领域。本系统“MVC新闻管理系统”就是基于这种模式构建的,旨在提供高效、模块化的新闻内容管理...