Logged user based connection string in .NET Core
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
add a comment |
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
add a comment |
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
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
.net-core asp.net-identity multi-tenant dbcontext asp.net-core-1.1
asked Nov 14 '18 at 10:31
nickornottonickornotto
4731238
4731238
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
With the defalut ASP.NET Identity template , you can :
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; }
}
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; }
}
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 inAspNetUsers
table.
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;
}
}
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>();
Then you could access the claims like :
var connectString = User.Claims.FirstOrDefault(c => c.Type == "CustomerConnectionString").Value;
Modify the creating/editing user view/controller , add the customer dropdownlist on view , get the custom id in
Register
function inAccountController
, query the connectingString of custom from db , and save inApplicationUser
object :
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
With the defalut ASP.NET Identity template , you can :
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; }
}
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; }
}
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 inAspNetUsers
table.
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;
}
}
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>();
Then you could access the claims like :
var connectString = User.Claims.FirstOrDefault(c => c.Type == "CustomerConnectionString").Value;
Modify the creating/editing user view/controller , add the customer dropdownlist on view , get the custom id in
Register
function inAccountController
, query the connectingString of custom from db , and save inApplicationUser
object :
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
add a comment |
With the defalut ASP.NET Identity template , you can :
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; }
}
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; }
}
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 inAspNetUsers
table.
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;
}
}
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>();
Then you could access the claims like :
var connectString = User.Claims.FirstOrDefault(c => c.Type == "CustomerConnectionString").Value;
Modify the creating/editing user view/controller , add the customer dropdownlist on view , get the custom id in
Register
function inAccountController
, query the connectingString of custom from db , and save inApplicationUser
object :
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
add a comment |
With the defalut ASP.NET Identity template , you can :
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; }
}
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; }
}
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 inAspNetUsers
table.
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;
}
}
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>();
Then you could access the claims like :
var connectString = User.Claims.FirstOrDefault(c => c.Type == "CustomerConnectionString").Value;
Modify the creating/editing user view/controller , add the customer dropdownlist on view , get the custom id in
Register
function inAccountController
, query the connectingString of custom from db , and save inApplicationUser
object :
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
With the defalut ASP.NET Identity template , you can :
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; }
}
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; }
}
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 inAspNetUsers
table.
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;
}
}
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>();
Then you could access the claims like :
var connectString = User.Claims.FirstOrDefault(c => c.Type == "CustomerConnectionString").Value;
Modify the creating/editing user view/controller , add the customer dropdownlist on view , get the custom id in
Register
function inAccountController
, query the connectingString of custom from db , and save inApplicationUser
object :
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
answered Nov 15 '18 at 7:47
Nan YuNan Yu
6,7352755
6,7352755
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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