[英]How to get HttpServletRequest information from UserDetailsService
I'm working with spring security and I have implemented my costume UserDetailsService.loadUserByUsername that returns a costume UserDetails.我正在使用 spring 安全性,并且我已经实现了返回服装 UserDetails 的服装 UserDetailsService.loadUserByUsername。 My problem is that I want in my UserDetailsService implementation to get information from the HttpServletRequest, more specific I would like to get
request.getLocale();
我的问题是我想在我的 UserDetailsService 实现中从 HttpServletRequest 中获取信息,更具体地说,我想获取
request.getLocale();
How can i do this?我怎样才能做到这一点?
You should be able (depending on your config) to use 您应该能够(取决于您的配置)使用
LocaleContextHolder.getLocaleContext().getLocale();
LocaleContextHolder
stores a static
ThreadLocal
object that stores the Locale
for your request. LocaleContextHolder
存储一个static
ThreadLocal
对象,该对象存储您的请求的Locale
。
You might have to register a RequestContextListener
with your Servlet container. 您可能必须在Servlet容器中注册一个
RequestContextListener
。
您可以将其从控制器传递到Service,并向Service添加新参数
I'm leaving this for others as I could not find the answer elsewhere.我将其留给其他人,因为我在其他地方找不到答案。 After some tinkering, I found that you can just add the request to the bean as such:
经过一番修改,我发现您可以像这样将请求添加到 bean:
@Configuration
public class SecurityConfig {
@Bean
public UserDetailsService userDetailsService(MyRepository repository, HttpServletRequest request) {
return username -> {
UserDetails userDetails = repository.findByEmail(username);
if (userDetails != null) {
log.info("login." + userDetails);
return userDetails;
}
String locale = request.getLocale().getDisplayName();
String message = "not.found[" + username + "].locale[" + locale + "]";
log.error(message);
throw new UsernameNotFoundException(message);
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.