这两天Spring用户登录国际化这个问题困扰我好久啊,于昨天晚上终于把它干掉了。

场景就是我们公司的产品-incopat,需要支持中英文,用户登录这块用的spring自带的security,需求讲的通俗一点就是,中文版提示中文提示信息,英文版提示英文版信息,废话不多说,见代码。

首先配置文件

security-config.xml

 <beans:bean id="customUsernamePasswordAuthenticationFilter"
class="com.incoshare.base.security.CustomUsernamePasswordAuthenticationFilter"
p:authenticationManager-ref="authenticationManager"
p:filterProcessesUrl="/doLogin" p:sessionAuthenticationStrategy-ref="compositeSessionAuthenticationStrategy"
p:authenticationSuccessHandler-ref="authenticationSuccessHandler"
p:authenticationFailureHandler-ref="authenticationFailureHandler"
p:rememberMeServices-ref="rememberMeServices"
p:authenticationDetailsSource-ref="customWebAuthenticationDetailsSource">
</beans:bean> <beans:bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="basename"
value="classpath:messages/security/messages" />
</beans:bean>

配置文件只贴了关键部分,第一个bean 配置登录的过滤器,第二个bean加载messages文件(这里有需要注意的地方如果想引用自己的message文件,建好文件后提供相对地址就可以了,classpath必须要哦!文件命名也是有规则的,message_en  就是下划线带上语言简称,这个简称需要跟网站上切换中英文标示一致),配置文件就这些

下面贴上过滤器代码

 package com.incoshare.base.security;

 import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.incoshare.base.util.PropertyUtil;
import com.incoshare.base.util.Utils;
import com.incoshare.incopat4.model.User;
import com.incoshare.incopat4.service.usermanager.UserListService;
import com.incoshare.util.EncryptUtils;
import com.incoshare.util.SingleLoginUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.util.WebUtils; import com.incoshare.base.util.RegexUtil; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale; public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{ static Logger logger = LoggerFactory
.getLogger(CustomUsernamePasswordAuthenticationFilter.class); private boolean postOnly = true; private byte[] keyBytes = { 0x21, 0x12, 0x4F, 0x58, (byte) 0x88, 0x09, 0x40, 0x38, 0x74,
0x25, (byte) 0x99, 0x21, (byte) 0xCB, (byte) 0xDD, 0x58, 0x66, 0x77, 0x22, 0x74,
(byte) 0x98, 0x30, 0x40, 0x36, (byte) 0xE2 };
private byte[] keyBytesForSjz = { 0x22, 0x12, 0x4F, 0x58, (byte) 0x88, 0x09, 0x40, 0x38, 0x74,
0x25, (byte) 0x99, 0x21, (byte) 0xCB, (byte) 0xDD, 0x48, 0x66, 0x77, 0x22, 0x74,
(byte) 0x98, 0x30, 0x40, 0x36, (byte) 0xE2 };
@Autowired
UserListService userListService;
@Autowired
PropertyUtil propertyUtil; @Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String newLocale = request.getParameter("locallangue");
if (newLocale != null) {
Locale locale = StringUtils.parseLocaleString(newLocale);
WebUtils.setSessionAttribute(request,
SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);
LocaleContextHolder.setLocale(locale, true);
}
//这块代码就是通过获取前台返回的语言编码,设置到spring的localeContextHolder里
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
} String username = obtainUsername(request);
String password = obtainPassword(request); //集慧智佳用户登录
String token = request.getParameter("token");
//石家庄单点登录
String tokenForSjz = request.getParameter("tokenForSjz");
if(Utils.isNotNull(token) || Utils.isNotNull(tokenForSjz)){
boolean judge = true;
if(Utils.isNull(token)){
judge = false;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
Date date = new Date();
String dateStr = simpleDateFormat.format(date);
String decodeToken = "";
String decryptJudge = "";
if(judge){
decodeToken = EncryptUtils.DataDecrypt(keyBytes, token);
decryptJudge = token;
}else{
decodeToken = EncryptUtils.DataDecrypt(keyBytesForSjz, tokenForSjz);
decryptJudge = tokenForSjz;
};
if(!decodeToken.equals(decryptJudge.trim()) && decodeToken.equals(dateStr.trim())){ User user = userListService.queryUserJhzj(username);
if(Utils.isNotNull(user)){
if(Utils.isNotNull(user.getOrganizationId())){
if(judge){
String jhzjOrid=propertyUtil.getContextProperty("jhzjOrid");
String pwd = propertyUtil.getContextProperty("jhzjPassword").trim();
if(user.getOrganizationId().equals(Integer.parseInt(jhzjOrid.trim()))){
password = pwd;
}
}else{
if(Utils.isNotNull(password)){
String record = password;
String orid = propertyUtil.getContextProperty("sjzOrid").trim();
password = EncryptUtils.DataDecrypt(keyBytesForSjz,password);
if(record.equals(password) || !String.valueOf(user.getOrganizationId()).equals(orid)){
password = "";
}
}
} }
} }else{
password = "";
}
} String tokenForLogin = request.getParameter("tokenForLogin");
if(Utils.isNotNull(tokenForLogin)){
String companyName = request.getParameter("companyName");
String record = password;
tokenForLogin = tokenForLogin.replaceAll(" ","+");
password = SingleLoginUtils.decryptPassword(username,password,tokenForLogin,companyName,userListService,propertyUtil,logger);
if(Utils.isNull(password)){
logger.info("{}:密码解密为空。账号{},没有解密的密码:{}",companyName,username,record);
}
}
if (username == null) {
username = "";
} if (password == null) {
password = "";
} username = username.trim(); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); if(!StringUtils.isEmpty(request.getParameter("iplogin"))) {
username = RegexUtil.getRealIp(request);
password="";
authRequest = new IpUserAuthenticationToken(username,password);
} this.logger.info("user:{},ip:{} trying to login",new Object[]{username,RegexUtil.getRealIp(request)}); // Allow subclasses to set the "details" property
setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest);
}
}

这块先声明下,代码不是我写的,看着很乱很糟糕吧。主要上边标黄的两个地方就可以了。

值设置后会通过this.getAuthenticationManager().authenticate(authRequest) 去初始化,喜欢研究源码的朋友看一跟一下看看

org.springframework.context.i18n.LocaleContextHolder这个类

 public static LocaleContext getLocaleContext() {
LocaleContext localeContext = localeContextHolder.get();
if (localeContext == null) {
localeContext = inheritableLocaleContextHolder.get();//这里会把你设置的值放到Spring 容器
}
return localeContext;
}

好了,关键的地方都说完了,这几天搞了这么久,写完了也没多少东西,代码就是这么美妙,解决问题的过程是漫长苦恼的,但最终解决有可能就一两行代码的事。

关于这一块有问题的可以随时沟通。

最新文章

  1. 网易测试分享会——“一起打造你想要的QA团队”
  2. Android - ViewPager+Fragment初始化问题
  3. SUSE Linux下新建Weblogic 10.3非admin服务
  4. linux 管道命令 竖线 ‘ | ’
  5. WebApi中直接返回json字符串的方法
  6. extjs Combobox动态加载数据问题,mode:local 还是remote
  7. 【组队训练】2015-2016 ACM-ICPC, NEERC, Southern Subregional Contest
  8. 01-android快速入门
  9. dispatch_async 与 dispatch_get_global_queue 的使用方法
  10. [转载]CSS 创作指南(Beta)(css规范)
  11. android CTS测试
  12. CI Weekly #14 | 如何搭建合适的持续交付开发流程?
  13. 封装bootstrap-treegrid组件
  14. 微软云Linux服务器 Mysql、tomcat远程连接错误解决办法
  15. html5 jqueryrotate插件实现旋转动画
  16. 浏览器仿EXCEL表格插件 版本更新 - 智表ZCELL产品V1.3.2更新
  17. 用static声明外部变量与内、外部函数
  18. prometheus和metrucs-server (k8s监控)
  19. python中TCP粘包问题解决方案
  20. ASP_NET实现界面无刷新的DropdownList两级联动效果

热门文章

  1. SSH配置免密登录
  2. Django创建和配置文件
  3. opus代码解析
  4. C语言中全局结构体指针隐含的错误
  5. Testing - 软件测试知识梳理 - 测试模型
  6. Python——破解极验滑动验证码
  7. Xamarin.Android 调用原生的Jar包
  8. MySQL笔记(8)---备份与恢复
  9. Python -- queue队列模块
  10. 获取 BaiduMapSDKDemo SHA1 签名