ASP.NET WebForm(.NET4.8)中用Microsoft.AspNet.Identity保护文件夹及添加角色
ASP.NET WebForm(.NET Framework 4.8)集成Microsoft.AspNet.Identity实用方案
一、用Microsoft.AspNet.Identity保护Admin文件夹
在.NET Framework 4.8的WebForm中,可结合web.config授权配置与Identity认证体系实现文件夹保护,步骤如下:
- 根目录web.config认证配置
确保根web.config中已配置Forms认证,指向登录页面:
<system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/Login.aspx" timeout="2880" /> </authentication> </system.web>
- Admin文件夹下添加web.config
在Admin文件夹内新建web.config,配置授权规则,拒绝匿名访问并仅允许指定角色进入:
<?xml version="1.0"?> <configuration> <system.web> <authorization> <deny users="?" /> <!-- 阻止所有匿名用户 --> <allow roles="Admin" /> <!-- 仅允许Admin角色用户访问 --> </authorization> </system.web> </configuration>
- 登录页面后台验证逻辑
在Login.aspx后台代码中,完成用户验证后生成Identity并登录:
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Owin.Security; protected void btnLogin_Click(object sender, EventArgs e) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var user = userManager.Find(txtUsername.Text.Trim(), txtPassword.Text.Trim()); if (user != null) { var identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = chkRememberMe.Checked }, identity); Response.Redirect("~/Admin/Default.aspx"); } else { lblError.Text = "用户名或密码错误"; } } private IAuthenticationManager AuthenticationManager { get { return HttpContext.Current.GetOwinContext().Authentication; } }
二、在Microsoft.AspNet.Identity中添加与管理角色
1. 准备实体与DbContext
定义自定义角色实体(可扩展属性),并配置关联角色的DbContext:
// 自定义角色类 public class ApplicationRole : IdentityRole { public ApplicationRole() : base() { } public ApplicationRole(string roleName) : base(roleName) { } } // 配置DbContext public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> { public ApplicationDbContext() : base("DefaultConnection") { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } }
2. 创建角色
在后台管理页面(如Admin/Roles.aspx)添加创建角色的逻辑:
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; protected void btnCreateRole_Click(object sender, EventArgs e) { var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(new ApplicationDbContext())); string roleName = txtRoleName.Text.Trim(); if (!roleManager.RoleExists(roleName)) { var role = new ApplicationRole(roleName); var createResult = roleManager.Create(role); if (createResult.Succeeded) { lblMessage.Text = "角色创建成功"; } else { foreach (var error in createResult.Errors) { lblMessage.Text += $"{error}<br/>"; } } } else { lblMessage.Text = "该角色已存在"; } }
3. 给用户分配角色
在用户管理页面添加角色分配逻辑:
protected void btnAssignRole_Click(object sender, EventArgs e) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var user = userManager.FindByEmail(txtUserEmail.Text.Trim()); string roleName = txtRoleName.Text.Trim(); if (user != null) { var assignResult = userManager.AddToRole(user.Id, roleName); if (assignResult.Succeeded) { lblMessage.Text = "角色分配成功"; } else { foreach (var error in assignResult.Errors) { lblMessage.Text += $"{error}<br/>"; } } } else { lblMessage.Text = "未找到指定用户"; } }
4. 配置Owin中间件
添加Startup.cs,配置Identity的Owin服务:
using Microsoft.Owin; using Owin; using Microsoft.AspNet.Identity; [assembly: OwinStartup(typeof(YourAppName.Startup))] namespace YourAppName { public class Startup { public void Configuration(IAppBuilder app) { app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<UserManager<ApplicationUser>>(UserManager<ApplicationUser>.Create); app.CreatePerOwinContext<RoleManager<ApplicationRole>>(RoleManager<ApplicationRole>.Create); app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login.aspx") }); } } }
内容的提问来源于stack exchange,提问作者Learning
相关产品推荐
相关产品推荐

