分区式多租户Spring应用中如何在自定义登录语句中获取tenant_id
分区式多租户Spring应用的登录SQL租户ID获取问题
我有一个接近完成的(分区式)多租户Spring应用,仅剩自定义登录语句这一难题。不同租户应允许使用相同的用户名,以下是示例代码,核心问题是如何在SQL中获取从URL解析的当前tenant_id值?
@Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .dataSource(dataSource) .usersByUsernameQuery("select username, password, enabled from user where username=? and tenant_id='howtodothis'") .authoritiesByUsernameQuery("select username, role from user where username=? and tenant_id='howtodothis'"); }
变通方案:将租户ID嵌入登录用户名
尚未解决原问题,但找到了一种变通思路:不在WHERE子句中添加租户信息,而是将其加入登录用户名。
Spring Security的登录操作发生在所有过滤器之前,因此TenantFilter可以从登录用户名中解析租户信息。通过在用户名前添加租户ID前缀,使用tenant/username作为登录用户名,对应的配置代码如下:
@Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .dataSource(dataSource) .usersByUsernameQuery("select concat(tenant_id, '/', username) as username, password, enabled from user where username=?") .authoritiesByUsernameQuery("select concat(tenant_id, '/', username) as username, role from user where username=?"); }
这意味着需要在某些地方将登录用户名拆分为租户ID和实际用户名,但也无需配置域名;应用完全基于登录实现多租户,甚至用户表本身也是租户感知的。不过,原问题仍未得到解答,该方案不适用于基于主机名实现的场景。
内容的提问来源于stack exchange,提问作者tbeernot
相关产品推荐
相关产品推荐

