如何将IdentityServer v3 / v4集成到MVC中以管理用户角色和声明?

时间:2016-06-15 15:47:20

标签: asp.net-mvc identityserver3

在ASP.NET 2005(v2时间帧)中,有一个名为ASP.NET网站管理工具的基于Web的工具,人们可以使用编辑用户并通常管理ASP.NET成员资格数据库。这个有用的工具在2012年被删除,但仍然遗漏。

http://www.hanselman.com/blog/ThinktectureIdentityManagerAsAReplacementForTheASPNETWebSiteAdministrationTool.aspx

编辑 - 要将自定义角色集成到我的MVC应用程序中,正确的版本不是服务器,需要使用IdentityManager

https://github.com/IdentityManager/IdentityManager.AspNetIdentity

编译解决方案。在Web.config中修改到工作的SQL数据库。在我的情况下,我已经有一些必须删除的aspIdentity表  实体可以创建新的实体。现在,此身份管理器代码应运行并用于创建用户,设置角色和声明并保存到表。

现在的目标是匹配数据库表和身份验证方案,以便其他一些新的MVC项目在此处查找其角色。该  目前,IdentityManager软件将是一个用于设置角色的实用程序。

在MVC应用程序中转到Tools,NuGet,查找“identitymanager”,应该有3个beta文件。获得身份管理员和aspIdentity。 项目还需要Owin(但我已经安装了这个)。修改Startup.cs:

       Public partial class Startup
       {
         public void Configuration(IAppBuilder app)
         {
                ConfigureAuth(app);

                app.Map("/idm", idm =>
                {
                    var factory = new IdentityManagerServiceFactory();
                    factory.IdentityManagerService = new Registration<IIdentityManagerService, ApplicationIdentityManagerService>();
                    factory.Register(new IdentityManager.Configuration.Registration<ApplicationUserManager>());
                    factory.Register(new IdentityManager.Configuration.Registration<ApplicationUserStore>());
                    factory.Register(new IdentityManager.Configuration.Registration<ApplicationDbContext>());
                    factory.Register(new IdentityManager.Configuration.Registration<ApplicationRoleManager>());
                    factory.Register(new IdentityManager.Configuration.Registration<ApplicationRoleStore>());

                    idm.UseIdentityManager(new IdentityManagerOptions
                    {
                        Factory = factory
                    });
                });
            }
        }

创建这些类,

                 public class ApplicationUserStore : UserStore<ApplicationUser>
          {
              public ApplicationUserStore(ApplicationDbContext ctx)
                  : base(ctx)
              {

              }

          }
          //  public class ApplicationRole :

          public class ApplicationRoleStore : RoleStore<IdentityRole>
          {
              public ApplicationRoleStore(ApplicationDbContext ctx)

                  : base(ctx)
              {
              }


          }

          public class ApplicationRoleManager : RoleManager<IdentityRole>
          {
              public ApplicationRoleManager(ApplicationRoleStore roleStore)
                  : base(roleStore)
              {

              }
          }

          public class ApplicationIdentityManagerService : AspNetIdentityManagerService<ApplicationUser, string, IdentityRole, string>
          {
              public ApplicationIdentityManagerService(ApplicationUserManager userMgr, ApplicationRoleManager roleMgr)
                  : base(userMgr, roleMgr)
              {

              }
          }

然后在IdentityConfig.cs中修改ApplicationUserManager类

        // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
        public class ApplicationUserManager : UserManager<ApplicationUser>
        {
          //  public ApplicationUserManager(IUserStore<ApplicationUser> store)


            public ApplicationUserManager(ApplicationUserStore store)
                : base(store)
            {
            }

            public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
            {
               // var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
                var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<ApplicationDbContext>()));

ConfigureAuth方法:

 public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });            
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");

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

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

        //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        //{
        //    ClientId = "",
        //    ClientSecret = ""
        //});
    }

此时,该实用程序指向与正在运行的MVC应用程序相同的SQL路径。应该共享“身份验证”,并且应该在“身份验证”中工作 MVC应用程序。如果我创建了我的用户帐户,创建了一个名为Finance的角色?然后返回并编辑用户,并添加名为Finance的新角色, 并在MVC控制器中放置:

     [Authorize(Roles ="Finance")]

该角色是由实用程序创建的,存储在SQL中,然后我的MVC希望能够查看,使用,获取或应用此角色,并且只允许我的用户帐户 授权。

现在,它不会授权,并将浏览器发送回登录,因为授权失败而不得不承担它。

如此接近但是什么可能使这不起作用?

1 个答案:

答案 0 :(得分:1)

Identity Server(OpenID Connect Provider)和Identity Manager(您使用的身份管理工具)在2015年某个时候删除了Thinktecture前缀。您可能因此使用了过时的nuget包。

此外,Identity Server 4使用.NET Core,Identity Server 3和Identity Manager使用.NET Framework。

如果您正在寻找有关Identity Manager入门的最新指南,我今年早些时候在我的博客上发布了演练:https://www.scottbrady91.com/ASPNET-Identity/Identity-Manager-using-ASPNET-Identity