Logged user based connection string in .NET Core












0















I have an application that uses identity database to store users and customers.



Each customer has also a separate database with its data and its connection string is stored in Customer table in the identity database.



AspNetUsers has a field to tell which customer the user belongs to (also identity db).



I want to assign connection string to the user when he logs in and make it available in the application for the duration of the session.



I currently have customer model:



public partial class `Customer`
{
public int Id { get; set; }
public string Name { get; set; }
public int NoLicenses { get; set; }
public bool? Enabled { get; set; }
public string CustomerConnectionString { get; set; }
}


and user model:



public class ApplicationUser : IdentityUser
{
public string CustomerId { get; set; }

public bool? IsEnabled { get; set; }

// there ideally I'd have a connstring property
}


The models map db table fields.



I'm using .NET Core 1.1 and EF Core.










share|improve this question



























    0















    I have an application that uses identity database to store users and customers.



    Each customer has also a separate database with its data and its connection string is stored in Customer table in the identity database.



    AspNetUsers has a field to tell which customer the user belongs to (also identity db).



    I want to assign connection string to the user when he logs in and make it available in the application for the duration of the session.



    I currently have customer model:



    public partial class `Customer`
    {
    public int Id { get; set; }
    public string Name { get; set; }
    public int NoLicenses { get; set; }
    public bool? Enabled { get; set; }
    public string CustomerConnectionString { get; set; }
    }


    and user model:



    public class ApplicationUser : IdentityUser
    {
    public string CustomerId { get; set; }

    public bool? IsEnabled { get; set; }

    // there ideally I'd have a connstring property
    }


    The models map db table fields.



    I'm using .NET Core 1.1 and EF Core.










    share|improve this question

























      0












      0








      0








      I have an application that uses identity database to store users and customers.



      Each customer has also a separate database with its data and its connection string is stored in Customer table in the identity database.



      AspNetUsers has a field to tell which customer the user belongs to (also identity db).



      I want to assign connection string to the user when he logs in and make it available in the application for the duration of the session.



      I currently have customer model:



      public partial class `Customer`
      {
      public int Id { get; set; }
      public string Name { get; set; }
      public int NoLicenses { get; set; }
      public bool? Enabled { get; set; }
      public string CustomerConnectionString { get; set; }
      }


      and user model:



      public class ApplicationUser : IdentityUser
      {
      public string CustomerId { get; set; }

      public bool? IsEnabled { get; set; }

      // there ideally I'd have a connstring property
      }


      The models map db table fields.



      I'm using .NET Core 1.1 and EF Core.










      share|improve this question














      I have an application that uses identity database to store users and customers.



      Each customer has also a separate database with its data and its connection string is stored in Customer table in the identity database.



      AspNetUsers has a field to tell which customer the user belongs to (also identity db).



      I want to assign connection string to the user when he logs in and make it available in the application for the duration of the session.



      I currently have customer model:



      public partial class `Customer`
      {
      public int Id { get; set; }
      public string Name { get; set; }
      public int NoLicenses { get; set; }
      public bool? Enabled { get; set; }
      public string CustomerConnectionString { get; set; }
      }


      and user model:



      public class ApplicationUser : IdentityUser
      {
      public string CustomerId { get; set; }

      public bool? IsEnabled { get; set; }

      // there ideally I'd have a connstring property
      }


      The models map db table fields.



      I'm using .NET Core 1.1 and EF Core.







      .net-core asp.net-identity multi-tenant dbcontext asp.net-core-1.1






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 14 '18 at 10:31









      nickornottonickornotto

      4731238




      4731238
























          1 Answer
          1






          active

          oldest

          votes


















          0














          With the defalut ASP.NET Identity template , you can :





          1. extend the ApplicationUser class in Models folder :



            public class ApplicationUser : IdentityUser
            {
            public string CustomerId { get; set; }

            public bool? IsEnabled { get; set; }

            //add your custom claims
            public string CustomerConnectionString { get; set; }
            }



          2. Add your custom model to ApplicationDbContext in Data folder :



            public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
            {
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
            {
            }

            protected override void OnModelCreating(ModelBuilder builder)
            {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);


            }

            public DbSet<Customer> Customers { get; set; }
            }


          3. Sync your database : Add-Migration xxxx , then run the Update-Database command in Package Manager Console . Now you have the Customer table and have CustomerConnectionString column in AspNetUsers table.



          4. Create you own implementation of IUserClaimsPrincipalFactory by inheriting the default one to generate a ClaimsPrincipal from your user :



            public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
            {
            public AppClaimsPrincipalFactory(
            UserManager<ApplicationUser> userManager
            , RoleManager<IdentityRole> roleManager
            , IOptions<IdentityOptions> optionsAccessor)
            : base(userManager, roleManager, optionsAccessor)
            { }

            public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
            {
            var principal = await base.CreateAsync(user);

            if (!string.IsNullOrWhiteSpace(user.CustomerId))
            {

            ((ClaimsIdentity)principal.Identity).AddClaims(new {
            new Claim("customid", user.CustomerId)
            });
            }

            if (!string.IsNullOrWhiteSpace(user.CustomerConnectionString))
            {

            ((ClaimsIdentity)principal.Identity).AddClaims(new {
            new Claim("CustomerConnectionString", user.CustomerConnectionString)
            });
            }
            return principal;
            }
            }



          5. Register the custom factory you just created in your application startup class, after adding Identity service:



            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddScoped<Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();



          6. Then you could access the claims like :



            var connectString = User.Claims.FirstOrDefault(c => c.Type == "CustomerConnectionString").Value;



          7. Modify the creating/editing user view/controller , add the customer dropdownlist on view , get the custom id in Register function in AccountController , query the connectingString of custom from db , and save in ApplicationUser object :



             var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await _userManager.CreateAsync(user, model.Password);







          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53298083%2flogged-user-based-connection-string-in-net-core%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            With the defalut ASP.NET Identity template , you can :





            1. extend the ApplicationUser class in Models folder :



              public class ApplicationUser : IdentityUser
              {
              public string CustomerId { get; set; }

              public bool? IsEnabled { get; set; }

              //add your custom claims
              public string CustomerConnectionString { get; set; }
              }



            2. Add your custom model to ApplicationDbContext in Data folder :



              public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
              {
              public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
              : base(options)
              {
              }

              protected override void OnModelCreating(ModelBuilder builder)
              {
              base.OnModelCreating(builder);
              // Customize the ASP.NET Identity model and override the defaults if needed.
              // For example, you can rename the ASP.NET Identity table names and more.
              // Add your customizations after calling base.OnModelCreating(builder);


              }

              public DbSet<Customer> Customers { get; set; }
              }


            3. Sync your database : Add-Migration xxxx , then run the Update-Database command in Package Manager Console . Now you have the Customer table and have CustomerConnectionString column in AspNetUsers table.



            4. Create you own implementation of IUserClaimsPrincipalFactory by inheriting the default one to generate a ClaimsPrincipal from your user :



              public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
              {
              public AppClaimsPrincipalFactory(
              UserManager<ApplicationUser> userManager
              , RoleManager<IdentityRole> roleManager
              , IOptions<IdentityOptions> optionsAccessor)
              : base(userManager, roleManager, optionsAccessor)
              { }

              public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
              {
              var principal = await base.CreateAsync(user);

              if (!string.IsNullOrWhiteSpace(user.CustomerId))
              {

              ((ClaimsIdentity)principal.Identity).AddClaims(new {
              new Claim("customid", user.CustomerId)
              });
              }

              if (!string.IsNullOrWhiteSpace(user.CustomerConnectionString))
              {

              ((ClaimsIdentity)principal.Identity).AddClaims(new {
              new Claim("CustomerConnectionString", user.CustomerConnectionString)
              });
              }
              return principal;
              }
              }



            5. Register the custom factory you just created in your application startup class, after adding Identity service:



              // Add framework services.
              services.AddDbContext<ApplicationDbContext>(options =>
              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

              services.AddIdentity<ApplicationUser, IdentityRole>()
              .AddEntityFrameworkStores<ApplicationDbContext>()
              .AddDefaultTokenProviders();

              services.AddScoped<Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();



            6. Then you could access the claims like :



              var connectString = User.Claims.FirstOrDefault(c => c.Type == "CustomerConnectionString").Value;



            7. Modify the creating/editing user view/controller , add the customer dropdownlist on view , get the custom id in Register function in AccountController , query the connectingString of custom from db , and save in ApplicationUser object :



               var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
              var result = await _userManager.CreateAsync(user, model.Password);







            share|improve this answer




























              0














              With the defalut ASP.NET Identity template , you can :





              1. extend the ApplicationUser class in Models folder :



                public class ApplicationUser : IdentityUser
                {
                public string CustomerId { get; set; }

                public bool? IsEnabled { get; set; }

                //add your custom claims
                public string CustomerConnectionString { get; set; }
                }



              2. Add your custom model to ApplicationDbContext in Data folder :



                public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
                {
                public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
                : base(options)
                {
                }

                protected override void OnModelCreating(ModelBuilder builder)
                {
                base.OnModelCreating(builder);
                // Customize the ASP.NET Identity model and override the defaults if needed.
                // For example, you can rename the ASP.NET Identity table names and more.
                // Add your customizations after calling base.OnModelCreating(builder);


                }

                public DbSet<Customer> Customers { get; set; }
                }


              3. Sync your database : Add-Migration xxxx , then run the Update-Database command in Package Manager Console . Now you have the Customer table and have CustomerConnectionString column in AspNetUsers table.



              4. Create you own implementation of IUserClaimsPrincipalFactory by inheriting the default one to generate a ClaimsPrincipal from your user :



                public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
                {
                public AppClaimsPrincipalFactory(
                UserManager<ApplicationUser> userManager
                , RoleManager<IdentityRole> roleManager
                , IOptions<IdentityOptions> optionsAccessor)
                : base(userManager, roleManager, optionsAccessor)
                { }

                public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
                {
                var principal = await base.CreateAsync(user);

                if (!string.IsNullOrWhiteSpace(user.CustomerId))
                {

                ((ClaimsIdentity)principal.Identity).AddClaims(new {
                new Claim("customid", user.CustomerId)
                });
                }

                if (!string.IsNullOrWhiteSpace(user.CustomerConnectionString))
                {

                ((ClaimsIdentity)principal.Identity).AddClaims(new {
                new Claim("CustomerConnectionString", user.CustomerConnectionString)
                });
                }
                return principal;
                }
                }



              5. Register the custom factory you just created in your application startup class, after adding Identity service:



                // Add framework services.
                services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

                services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

                services.AddScoped<Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();



              6. Then you could access the claims like :



                var connectString = User.Claims.FirstOrDefault(c => c.Type == "CustomerConnectionString").Value;



              7. Modify the creating/editing user view/controller , add the customer dropdownlist on view , get the custom id in Register function in AccountController , query the connectingString of custom from db , and save in ApplicationUser object :



                 var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await _userManager.CreateAsync(user, model.Password);







              share|improve this answer


























                0












                0








                0







                With the defalut ASP.NET Identity template , you can :





                1. extend the ApplicationUser class in Models folder :



                  public class ApplicationUser : IdentityUser
                  {
                  public string CustomerId { get; set; }

                  public bool? IsEnabled { get; set; }

                  //add your custom claims
                  public string CustomerConnectionString { get; set; }
                  }



                2. Add your custom model to ApplicationDbContext in Data folder :



                  public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
                  {
                  public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
                  : base(options)
                  {
                  }

                  protected override void OnModelCreating(ModelBuilder builder)
                  {
                  base.OnModelCreating(builder);
                  // Customize the ASP.NET Identity model and override the defaults if needed.
                  // For example, you can rename the ASP.NET Identity table names and more.
                  // Add your customizations after calling base.OnModelCreating(builder);


                  }

                  public DbSet<Customer> Customers { get; set; }
                  }


                3. Sync your database : Add-Migration xxxx , then run the Update-Database command in Package Manager Console . Now you have the Customer table and have CustomerConnectionString column in AspNetUsers table.



                4. Create you own implementation of IUserClaimsPrincipalFactory by inheriting the default one to generate a ClaimsPrincipal from your user :



                  public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
                  {
                  public AppClaimsPrincipalFactory(
                  UserManager<ApplicationUser> userManager
                  , RoleManager<IdentityRole> roleManager
                  , IOptions<IdentityOptions> optionsAccessor)
                  : base(userManager, roleManager, optionsAccessor)
                  { }

                  public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
                  {
                  var principal = await base.CreateAsync(user);

                  if (!string.IsNullOrWhiteSpace(user.CustomerId))
                  {

                  ((ClaimsIdentity)principal.Identity).AddClaims(new {
                  new Claim("customid", user.CustomerId)
                  });
                  }

                  if (!string.IsNullOrWhiteSpace(user.CustomerConnectionString))
                  {

                  ((ClaimsIdentity)principal.Identity).AddClaims(new {
                  new Claim("CustomerConnectionString", user.CustomerConnectionString)
                  });
                  }
                  return principal;
                  }
                  }



                5. Register the custom factory you just created in your application startup class, after adding Identity service:



                  // Add framework services.
                  services.AddDbContext<ApplicationDbContext>(options =>
                  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

                  services.AddIdentity<ApplicationUser, IdentityRole>()
                  .AddEntityFrameworkStores<ApplicationDbContext>()
                  .AddDefaultTokenProviders();

                  services.AddScoped<Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();



                6. Then you could access the claims like :



                  var connectString = User.Claims.FirstOrDefault(c => c.Type == "CustomerConnectionString").Value;



                7. Modify the creating/editing user view/controller , add the customer dropdownlist on view , get the custom id in Register function in AccountController , query the connectingString of custom from db , and save in ApplicationUser object :



                   var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                  var result = await _userManager.CreateAsync(user, model.Password);







                share|improve this answer













                With the defalut ASP.NET Identity template , you can :





                1. extend the ApplicationUser class in Models folder :



                  public class ApplicationUser : IdentityUser
                  {
                  public string CustomerId { get; set; }

                  public bool? IsEnabled { get; set; }

                  //add your custom claims
                  public string CustomerConnectionString { get; set; }
                  }



                2. Add your custom model to ApplicationDbContext in Data folder :



                  public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
                  {
                  public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
                  : base(options)
                  {
                  }

                  protected override void OnModelCreating(ModelBuilder builder)
                  {
                  base.OnModelCreating(builder);
                  // Customize the ASP.NET Identity model and override the defaults if needed.
                  // For example, you can rename the ASP.NET Identity table names and more.
                  // Add your customizations after calling base.OnModelCreating(builder);


                  }

                  public DbSet<Customer> Customers { get; set; }
                  }


                3. Sync your database : Add-Migration xxxx , then run the Update-Database command in Package Manager Console . Now you have the Customer table and have CustomerConnectionString column in AspNetUsers table.



                4. Create you own implementation of IUserClaimsPrincipalFactory by inheriting the default one to generate a ClaimsPrincipal from your user :



                  public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
                  {
                  public AppClaimsPrincipalFactory(
                  UserManager<ApplicationUser> userManager
                  , RoleManager<IdentityRole> roleManager
                  , IOptions<IdentityOptions> optionsAccessor)
                  : base(userManager, roleManager, optionsAccessor)
                  { }

                  public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
                  {
                  var principal = await base.CreateAsync(user);

                  if (!string.IsNullOrWhiteSpace(user.CustomerId))
                  {

                  ((ClaimsIdentity)principal.Identity).AddClaims(new {
                  new Claim("customid", user.CustomerId)
                  });
                  }

                  if (!string.IsNullOrWhiteSpace(user.CustomerConnectionString))
                  {

                  ((ClaimsIdentity)principal.Identity).AddClaims(new {
                  new Claim("CustomerConnectionString", user.CustomerConnectionString)
                  });
                  }
                  return principal;
                  }
                  }



                5. Register the custom factory you just created in your application startup class, after adding Identity service:



                  // Add framework services.
                  services.AddDbContext<ApplicationDbContext>(options =>
                  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

                  services.AddIdentity<ApplicationUser, IdentityRole>()
                  .AddEntityFrameworkStores<ApplicationDbContext>()
                  .AddDefaultTokenProviders();

                  services.AddScoped<Microsoft.AspNetCore.Identity.IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();



                6. Then you could access the claims like :



                  var connectString = User.Claims.FirstOrDefault(c => c.Type == "CustomerConnectionString").Value;



                7. Modify the creating/editing user view/controller , add the customer dropdownlist on view , get the custom id in Register function in AccountController , query the connectingString of custom from db , and save in ApplicationUser object :



                   var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                  var result = await _userManager.CreateAsync(user, model.Password);








                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 15 '18 at 7:47









                Nan YuNan Yu

                6,7352755




                6,7352755
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53298083%2flogged-user-based-connection-string-in-net-core%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Danny Elfman

                    Retrieve a Users Dashboard in Tumblr with R and TumblR. Oauth Issues