gpt4 book ai didi

java - RequestContextHolder.getRequestAttributes() null - Spring Security + Multi-Tenancy

转载 作者:行者123 更新时间:2023-11-30 07:48:34 27 4
gpt4 key购买 nike

<分区>

在实现 spring security(基本表单例份验证)后,我无法使用 RequestContextHolder.getRequestAttributes() 获取当前请求,之前它工作正常。

问题是 RequestContextHolder.getRequestAttributes() 为 null,我需要从登录请求中获取额外的参数(租户 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;
}
}

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com