RequestContextHolder.getRequestAttributes() null - Spring Security + Multi Tenant [关闭]
Posted
技术标签:
【中文标题】RequestContextHolder.getRequestAttributes() null - Spring Security + Multi Tenant [关闭]【英文标题】:RequestContextHolder.getRequestAttributes() null - Spring Security + Multi Tenant [closed] 【发布时间】:2018-08-11 12:46:49 【问题描述】:在实现spring security(基本表单身份验证)后,我无法使用RequestContextHolder.getRequestAttributes()
获取当前请求,这在之前运行良好。
问题是 RequestContextHolder.getRequestAttributes() 为空,我需要从登录请求中获取额外的参数(租户 ID)才能选择正确的数据库。
这是我的代码:
安全
@EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter
@Autowired
private MyUserDetailsService myUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception
http
.authorizeRequests()
.antMatchers("/assets/**")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/dashboard/login")
.defaultSuccessUrl("/dashboard/home")
.permitAll()
.and()
.logout()
.permitAll();
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception
auth.authenticationProvider(authenticationProvider());
@Bean
public DaoAuthenticationProvider authenticationProvider()
DaoAuthenticationProvider authProvider
= new DaoAuthenticationProvider();
authProvider.setUserDetailsService(myUserDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
@Bean
public PasswordEncoder passwordEncoder()
return new BCryptPasswordEncoder(11);
CurrentTenantIdentifierResolverImpl
public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver
Logger log = LogManager.getLogger(CurrentTenantIdentifierResolverImpl.class);
@Override
public String resolveCurrentTenantIdentifier()
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpSession session = attr.getRequest().getSession(false); // true == allow create
if (session != null)
String tenant = (String) session.getAttribute("tenant");
log.trace("Tenant default resolved in session is: " + tenant);
if (tenant != null)
return tenant;
String request = attr.getRequest().getRequestURI();
String tenant = attr.getRequest().getParameter("tenant");
if (request.equals("/dashboard/login") && tenant != null)
return tenant;
//otherwise return default tenant
log.trace("Tenant default not resolved in session");
return null;
@Override
public boolean validateExistingCurrentSessions()
return true;
【问题讨论】:
谢谢哥们!!你的代码工作完美。 【参考方案1】:我不小心删除了一个至关重要的课程。只需将其添加回来即可解决问题。
@Configuration
@WebListener
public class MyRequestContextListener extends RequestContextListener
【讨论】:
以上是关于RequestContextHolder.getRequestAttributes() null - Spring Security + Multi Tenant [关闭]的主要内容,如果未能解决你的问题,请参考以下文章