EF Core - multi tenant application with 2 DB Context - entity-framework-core

Background:
.NET 6 application (front-end Angular SPA) Will be deployed as single application with 1 database per tenant. There is a shared database (called GlobalContext) which holds Tenant and TenantUser information.
In my Program.cs I don't have a connection string to the tenant database, as that information information is only available after a user has logged in.
builder.Services.AddDbContext<GlobalContext>(
options => options.UseSqlServer(config.GetValue<string>("ConnectionStringGlobal"))
);
No connection string specified here
builder.Services.AddDbContext<FinanceAppContext>();
In the OnConfiguring method in the FinanceappContext I obtain the connection string using a service;
var tenant = await _tenantService.GetConnectionString();
optionsBuilder.UseSqlServer(_config.GetValue<string>(tenant));
base.OnConfiguring(optionsBuilder);
The TenantService is a transient service which obtains the logged in users tenant from the GlobalContext
public async Task<string> GetConnectionString() {
try
{
var userId = _contextAccessor.HttpContext.User.FindFirst(ClaimTypes.Email).Value;
var user = await _globalContext.TenantUser
.Include(tenantuser => tenantuser.Tenant)
.FirstOrDefaultAsync(tenantuser => tenantuser.EmailAddress == userId);
return user.Tenant.Name;
}
catch (System.Exception)
{
return "";
}
}
But when I try to access any data via the FinanceAppContext I get the following error;
A relational store has been configured without specifying either the DbConnection or connection string to use
It seems like the fact I don't specify a connection string in Program.cs and but do specify one in OnConfiguring seems to be an issue?

So the issue was that my OnConfiguring method was marked as async and I was making an await call to my TenantService to obtain the connection string. I remove the async/await and the retrieval of the user from the GlobalContext now works.

Related

Handle errors for federated users password update in keycloak

I am using keycloak custom user storage provider and users are getting from an external service.
The class implements the following interfaces:
public class CustomUserStorageProvider implements UserStorageProvider, UserLookupProvider, CredentialInputValidator, UserQueryProvider, CredentialInputUpdater {
When the user password is expired in isValid method the exception is catched and the requiredAction is added to prompt user to set a new password
UserModel userAdapter = loadedUsers.get(user.getUsername());
if (userAdapter != null) {
userAdapter.addRequiredAction(RequiredAction.UPDATE_PASSWORD);
return true;
}
The updateCredential method sends a request to an external service to update user password
#Override
public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) {
try {
updateUserPassword(user.getUsername(), input.getChallengeResponse());
} catch (Exception e) {
log.error("Something went wrong", e);
}
return true;
}
This works normally, updates the user password in an external service and authenticates user.
I need to display the according error message coming from an external service when something went wrong during the updating password e.g it doesn't meet the needs of the password policy(this is also defined in external service rather than in keycloak).
I researched but couldn't find a way how to do that.
Is there any way to achieve that?

How do I loosely couple the Blazor Identity scaffold with my own Database Context?

I've created a Blazor Server App with the option to scaffold an identity system. This created an Entity Framework IdentityDbContext with a number of tables to manage user logins and settings. I decided to keep my own DbContext separate from this so that I could replace either of the contexts later, if necessary.
What I would like to do is have a User entity in my own custom dbcontext, and in it store a reference to the user id of the scaffolded IdentityDbContext entity. I would also like to ensure that I don't have to query the db for the custom entity every time the user opens a new page.
I've been looking around StackOverflow trying to find good suggestions of how to approach this, but I'm still not sure how to start. So I have a few questions:
Is my approach a sensible one?
How do I find a permanent id number or string to couple with on the UserIdentity?
Should I store my custom user entity in some sort of context so I don't have to query it all the time? If so, how?
All help is greatly appreciated!
It looks like your requirement is to store custom information about the current user above and beyond what is stored in Identity about the current user.
For simpler use cases you can create your own User class derived from IdentityUser and add additional properties on there and let Identity take care of all persistence and retrieval.
For more complex use cases you may follow the approach you have taken, whereby you create your own tables to store user related information.
It seems that you have taken the second approach.
Is my approach a sensible one?
I think so. Burying lots of business-specific context about the user in the Identity tables would tightly bind you to the Identity implementation.
How do I find a permanent id number or string to couple with on the
UserIdentity?
IdentityUser user = await UserManager<IdentityUser>.FindByNameAsync(username);
string uniqueId = user.Id;
// or, if the user is signed in ...
string uniqueId = UserManager<IdentityUser>.GetUserId(HttpContext.User);
Should I store my custom user entity in some sort of context so I
don't have to query it all the time? If so, how?
Let's say you have a class structure from your own DbContext that stores custom information about the user, then you can retrieve that when the user signs in, serialize it, and put it in a claim on the ClaimsPrincipal. This will then be available to you with every request without going back to the database. You can deserialize it from the Claims collection as needed and use it as required.
How to ...
Create a CustomUserClaimsPrincipalFactory (this will add custom claims when the user is authenticated by retrieving data from ICustomUserInfoService and storing in claims):
public class CustomUserClaimsPrincipalFactory
: UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
private readonly ICustomUserInfoService _customUserInfoService;
public CustomUserClaimsPrincipalFactory(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
IOptions<IdentityOptions> optionsAccessor,
ICustomUserInfoService customUserInfoService)
: base(userManager, roleManager, optionsAccessor)
{
_customUserInfoService= customUserInfoService;
}
protected override async Task<ClaimsIdentity> GenerateClaimsAsync(
ApplicationUser user)
{
var identity = await base.GenerateClaimsAsync(user);
MyCustomUserInfo customUserInfo =
await _customUserInfoService.GetInfoAsync();
// NOTE:
// ... to add more claims, the claim type need to be registered
// ... in StartUp.cs : ConfigureServices
// e.g
//services.AddIdentityServer()
// .AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
// {
// options.IdentityResources["openid"].UserClaims.Add("role");
// options.ApiResources.Single().UserClaims.Add("role");
// options.IdentityResources["openid"].UserClaims.Add("my-custom-info");
// options.ApiResources.Single().UserClaims.Add("my-custom-info");
// });
List<Claim> claims = new List<Claim>
{
// Add serialized custom user info to claims
new Claim("my-custom-info", JsonSerializer.Serialize(customUserInfo))
};
identity.AddClaims(claims.ToArray());
return identity;
}
}
Register your CustomUserInfoService in Startup.cs (your own service to get your custom user info from the database):
services.AddScoped<ICustomUserInfoService>(_ => new CustomUserInfoService());
Register Identity Options (with your CustomUserClaimsPrincipalFactory and authorisation in Startup.cs. NOTE: addition of "my-custom-info" as a registered userclaim type. Without this your code in CustomUserInfoService will fail to add the claim type "my-custom-info":
services.AddDefaultIdentity<IdentityUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.User.RequireUniqueEmail = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options =>
{
options.IdentityResources["openid"].UserClaims.Add("role");
options.ApiResources.Single().UserClaims.Add("role");
options.IdentityResources["openid"].UserClaims.Add("my-custom-info");
options.ApiResources.Single().UserClaims.Add("my-custom-info");
});
You can then retrieve your custom user info from claims, without returning to database, by using:
MyCustomUserInfo customUserInfo =
JsonSerializer.Deserialize<MyCustomUserInfo>(
HttpContext.User.Claims
.SingleOrDefault(c => c.Type == "my-custom-info").Value);

ASP MVC EF6 Code first Multi tenant get tenant id

we keep fighting with out multi tenant application.
This is an ASP MVC EF6 Code First web application.
We initialize a list of tenants in the Application_Start, getting a pair of values:
Host
TenantId
So we can associate any host with one TenantId, and store that list in cache.
We have configured a custom filter to get the current tenant.
public class TenantActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Items.Add("TenantId", GetCurrentTenant(filterContext.HttpContext.Request.Url.Host));
base.OnActionExecuting(filterContext);
}
}
The GetCurrentTenant function just access the list in cache and get the current one based on the host passed.
Is it correct to store the current tenant in an item in the context?
After that, we have created an Interceptor to get any query and add a filter to filter by TenantId. This is done and working good, we just need to add the tenantId from the context:
The problem we have is where we get the TenantId for each request.
if (HttpContext.Current.CurrentHandler == null) return;
var clientId = Convert.ToInt32(HttpContext.Current.Items["ClientId"]);
foreach (DbParameter param in command.Parameters)
{
if (param.ParameterName != TenantAwareAttribute.TenantIdFilterParameterName)
continue;
param.Value = clientId;
}
We don't know if this is the correct approach since there is a lot of informationon the net.
Thanks.
In my experience, the persistence of the tenant Id in the HTTP context is not right, as in some cases, the HTTP context becomes null.
You can try to get the tenant Id from the claims of the current principal. Creating a static class with a tenant identifier property that reads from the claims and gives is more reliable. Assuming you are using the owin pipeline, this should be easy to do. You can take a look at the reference sample application from github here
It looks like the below block,
public static class UserContext
{
public static string TenantId
{
get
{
return Threading.Thread.CurrentPrincipal.FindFirst("tenantid");
}
}
}

Is this the right way to do stateless authentication per call on ServiceStack?

I have REST service requirements in which some calls require authentication and some don't. Absolutely no state is used, as the calls are all independent from one another. I have put something together which seems to work, but is this the right way to go about not using sessions?
This question is kind of related to my WCF question which is answered here.
Firstly I registered the authentication method:
Plugins.Add(new AuthFeature(() => new AuthUserSession(),
new IAuthProvider[] {
new CustomCredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
}
));
I then attribute the respective calls (or service or DTO) with the Authenticate attribute:
[Authenticate]
public HelloResponse Post(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name + " with POST & Auth"};
}
I inherit from the BasicAuthProvider class which does the authentication:
public class CustomCredentialsAuthProvider : BasicAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
return userName == "dylan" && password == "abc123";
}
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
session.IsAuthenticated = true;
//Important: You need to save the session!
authService.SaveSession(session, new TimeSpan(0,0,10));
}
}
As you can see, I do save the session but it times out after 10 seconds. This is the part that I'm sure can potentially be done better. It seems to work nicely though.
Is there a better way of doing what I'm trying to accomplish?
Is there also any way, due to the sessionless nature of these services, to remove the Auth, AssignRoles and UnassignRoles methods?
If you wanted to keep using ServiceStack's Authentication and Session support you could just add a response filter that clears the user session after the service is executed, e.g:
this.ResponseFilters.Add((req, res, dto) => req.RemoveSession());
Basically after each request is executed it clears the session, so no record of them having authenticated exists.
Otherwise you can just skip using ServiceStack's Authentication completely and just provide your own via RequestFitlers of FilterAttributes (which is essentially what SS Auth does under the hood).

Database permissions in MVC with NHibernate

I'm working on an intranet MVC web application, using Fluent NHibernate.
As everyone knows, creating the necessary ISessionFactory is heavy, and therefore should be done only once. Hence, I create it in the Global.asax file during Application_Start, then cache it in the application for future use.
The problem is that I only want to give access to users who already have permissions over the database.
This could theoretically be solved by defining Integrated Security=SSPI in the connection string (rather than by providing an SQL username and password).
However, this raises an error during Fluently.Configure, because the configuration occurs during Application_Start, which is being run by the process hosting the application, which does not have permissions to connect to the DB.
How do I solve this issue?
You could initialize it in BeginRequest instead of Application_Start:
private static bool _initialized = false;
private static object _syncRoot = new object();
protected void Application_BeginRequest(object source, EventArgs e)
{
if (_initialized)
{
return;
}
lock (_initialized)
{
if (_initialized)
{
return;
}
// Initialize the session factory here and cache it
_initialized = true;
}
}