コード例 #1
0
ファイル: IdentityHelpers.cs プロジェクト: lmxin123/Framework
        public static List <ParentMenuItem> GetUserRight(this IIdentity identity, string userId = null, bool requireNew = false)
        {
            if (!identity.IsAuthenticated && string.IsNullOrEmpty(userId))
            {
                //未登录或者登录信息己过期,请重新登录!
                HttpContext.Current.Response.RedirectPermanent(AuthSetting.LoginUrl, true);
                menus.Clear();
                return(menus);
            }

            string id = userId ?? identity.GetUserId();

            if (CACHE_USERID != id || requireNew)
            {
                CACHE_USERID = id;//这里一定要赋值

                using (var db = new AuthDbContext())
                {
                    //   var role =Applicat db.FirstOrDefault(item => item.UserId == CACHE_USERID);
                    var roles = UserManager.GetRoles(CACHE_USERID);
                    if (roles == null || roles.Count == 0)
                    {
                        throw new Exception("用户缺少权限!");
                    }

                    var roleRight = db.Roles.FirstOrDefault(item => item.Name == roles.FirstOrDefault());

                    if (string.IsNullOrEmpty(roleRight.Rights))
                    {
                        throw new Exception($"{roleRight.Name}角色还没有分配过任何权限!");
                    }

                    var userRight = JsonConvert.DeserializeObject <List <ParentRightItem> >(roleRight.Rights);
                    menus.Clear();
                    menus.AddRange(MenuManager.GetAllMenus());

                    menus.ForEach(menu =>
                    {
                        var right = userRight.FirstOrDefault(item => item.Code == menu.Code);
                        menu.All  = right.All;

                        menu.SubMenuList.ForEach(subMenu =>
                        {
                            var subRight = right.SubRightList.FirstOrDefault(subItem => subItem.SubCode == subMenu.SubCode);

                            subMenu.Auditing = subRight.Auditing ?? false;
                            subMenu.Create   = subRight.Create ?? false;
                            subMenu.Delete   = subRight.Delete ?? false;
                            subMenu.Select   = subRight.Select ?? false;
                            subMenu.Update   = subRight.Update ?? false;
                        });
                    });
                }
            }
            return(menus);
        }
コード例 #2
0
        // 有关配置身份验证的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=301864
        public virtual void ConfigureAuth(IAppBuilder app)
        {
            // 配置数据库上下文、用户管理器和登录管理器,以便为每个请求使用单个实例
            app.CreatePerOwinContext(AuthDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            // 使应用程序可以使用 Cookie 来存储已登录用户的信息
            // 并使用 Cookie 来临时存储有关使用第三方登录提供程序登录的用户的信息
            // 配置登录 Cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString(AuthSetting.LoginUrl),
                ExpireTimeSpan     = TimeSpan.FromMinutes(AuthSetting.ExpireTimeSpanInMinutes),
                Provider           = new CookieAuthenticationProvider
                {
                    // 当用户登录时使应用程序可以验证安全戳。
                    // 这是一项安全功能,当你更改密码或者向帐户添加外部登录名时,将使用此功能。
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(AuthSetting.ExpireTimeSpanInMinutes),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // 使应用程序可以在双重身份验证过程中验证第二因素时暂时存储用户信息。
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // 使应用程序可以记住第二登录验证因素,例如电话或电子邮件。
            // 选中此选项后,登录过程中执行的第二个验证步骤将保存到你登录时所在的设备上。
            // 此选项类似于在登录时提供的“记住我”选项。
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            IdentityDbInit.InitialSetup(AuthDbContext.Create());
            // 取消注释以下行可允许使用第三方登录提供程序登录
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
コード例 #3
0
ファイル: IdentityModels.cs プロジェクト: lmxin123/Framework
        public static void InitialSetup(AuthDbContext context)
        {
            // 初始化配置将放在这儿
            var userMgr = new ApplicationUserManager(new UserStore <ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>(context));
            var roleMgr = new ApplicationRoleManager(new RoleStore <ApplicationRole, string, IdentityUserRole>(context));
            var rigthts = RightManager.GetDefaultRights(true);

            if (!roleMgr.RoleExists(AuthSetting.AdminRoleName))
            {
                roleMgr.Create(new ApplicationRole
                {
                    Id       = Guid.NewGuid().ToString(),
                    Name     = AuthSetting.AdminRoleName,
                    Operator = AuthSetting.Administrator,
                    Remark   = "超级管理员角色,系统默认创建,不充许改动"
                });
            }
            else
            {
                var role = roleMgr.FindByName(AuthSetting.AdminRoleName);
                role.Rights = JsonConvert.SerializeObject(rigthts);
                roleMgr.Update(role);
            }

            ApplicationUser user = userMgr.FindByName(AuthSetting.Administrator);

            if (user == null)
            {
                userMgr.Create(new ApplicationUser
                {
                    Id       = Guid.NewGuid().ToString(),
                    UserName = AuthSetting.Administrator,
                    Email    = "*****@*****.**",
                    Operator = AuthSetting.Administrator,
                    Remark   = "超级管理员,系统默认创建,不充许改动"
                }, AuthSetting.AdminPassowrd);
                user = userMgr.FindByName(AuthSetting.Administrator);
            }

            if (!userMgr.IsInRole(user.Id, AuthSetting.AdminRoleName))
            {
                userMgr.AddToRole(user.Id, AuthSetting.AdminRoleName);
            }

            context.SaveChanges();
        }
コード例 #4
0
ファイル: IdentityModels.cs プロジェクト: lmxin123/Ad
        public static void InitialSetup(AuthDbContext context)
        {
            // 初始化配置将放在这儿
            ApplicationUserManager userMgr = new ApplicationUserManager(new UserStore <ApplicationUser>(context));
            ApplicationRoleManager roleMgr = new ApplicationRoleManager(new RoleStore <ApplicationRole>(context));

            string oper = "System";

            if (!roleMgr.RoleExists(AuthSetting.AdminRoleName))
            {
                roleMgr.Create(new ApplicationRole
                {
                    Name     = AuthSetting.AdminRoleName,
                    Operator = oper,
                    Rights   = JsonConvert.SerializeObject(RightManager.GetDefaultRights()),
                    Remark   = "系统默认创建,不充许改动"
                });
            }

            ApplicationUser user = userMgr.FindByName(AuthSetting.Administrator);

            if (user == null)
            {
                userMgr.Create(new ApplicationUser
                {
                    UserName = AuthSetting.Administrator,
                    Email    = "*****@*****.**",
                    Operator = oper,
                }, AuthSetting.AdminPassowrd);
                user = userMgr.FindByName(AuthSetting.Administrator);
            }

            if (!userMgr.IsInRole(user.Id, AuthSetting.AdminRoleName))
            {
                userMgr.AddToRole(user.Id, AuthSetting.AdminRoleName);
            }

            context.SaveChanges();
        }