【问题标题】:How to integrate IdentityServer v3/v4 into MVC to manage user Roles and Claims?如何将 IdentityServer v3/v4 集成到 MVC 中来管理用户角色和声明?
【发布时间】:2016-10-16 20:17:51
【问题描述】:

在 ASP.NET 2005(v2 时间范围)中有一个基于 Web 的工具,称为 ASP.NET 网站管理工具,人们可以使用编辑用户并通常管理 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 文件。获取 identitymanager 和 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 有望查看、使用、获取或应用此角色,并且只让我的用户帐户成为 授权。

现在,它不会授权,并将浏览器发送回登录,由于授权失败,必须假设它。

如此接近,但什么会使这不起作用?

【问题讨论】:

  • 如果您现在遇到身份验证/授权问题,查看您的 ConfigureAuth 方法会很有用。还是与带有个人帐户模板的默认 ASP.NET MVC 保持一致?
  • 我认为 ConfigureAuth 是默认的。将其添加到上面的原始内容中。

标签: asp.net-mvc identityserver3


【解决方案1】:

Identity Server(OpenID Connect 提供程序)和 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

【讨论】:

  • 感谢您的解释,看来这正是问题之一。而且我无法让您的链接在那里工作。一旦我意识到这是需要的身份“经理”,我就找到了不同的文档和这个视频,vimeo.com/125426951,现在正在尝试;但也期待您的演练
  • @BradRogers 链接对我来说似乎工作正常,除非您指的是链接中不起作用的示例代码。还要感谢 Scott Brady 的教程!
  • 是的,链接现在有效,我应该提到这一点。我似乎很难坚持使用 HTTPS。 Visual Studio 15 使用 IIS Express? Windows7有IIS管理器,是一样的吗?我制作了一个 SSL 证书,将我的文字项目文件夹路径添加到 IIS 管理器,错误。卡住了,因为现在将我的网站设置为 httpS,它返回空白,没有网页。
  • 好的,这是您的部署的问题。同时切换回 IIS Express,让我们一次解决一个问题。您可以通过双击属性、转到 Web 并将下拉框设置为 IIS Express 来完成此操作。
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2015-09-05
  • 2022-11-17
  • 2015-04-20
  • 2018-02-10
  • 1970-01-01
  • 2011-03-20
相关资源
最近更新 更多