自己需求如下(多种用户登录):
后端pc管理员账号、手机app用户,若依框架使用springsecurity框架到验证数据库那一步只能继承UserDetailsService(String username)这个方法,而且只能传递一个username,由于我是多张用户表,就自己想了个方案解决这个问题(把username改成JSON:{username:"admin",userType:"admin"}字符串),为了尽量少改若依原框架,且满足自己项目需求。熟悉springsecurity的可以修改增加filter、provider、token以及Config等新增一条鉴权路线。尽量写详细,还有不懂的可以留言评论。
思路如下:
1. 前端pc端request中header中存放“userType”:“admin”
2. app中request中header中存放“userType”:“user”
3. 若依中springsecurity的拦截器中获取这个token,如果判断是手机app(即“userType=user”)则每次访问自动刷新token 有效期(手机端需要持续登录),如果pc端(即“userType=admin”)则token有效期30分钟。【 ruoyi-framework模块中com.ruoyi.framework.web.service.JwtAuthenticationTokenFilter.java】
4.传到UserDetailsService(String username)中 把username改成{username:"admin",userType:"admin"},进入方法后再把json中的username字符串解析拆分出来,这样就可以传入userType字段,来判断查询哪一张表的数据。
注意:下文中
/************添加部分**************/
/************添加部分**************/
中间的部分是修改的代码
public class NameHelper {
private String name;
private String userType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
}
/**
* 获取请求token
*
* @param request
* @return token
*/
public String getType(HttpServletRequest request)
{
String userType = request.getHeader("userType");
/*if (Validator.isNotEmpty(userType))
{
userType = userType.replace(Constants.TOKEN_PREFIX, "");
}*/
return userType;
}
/**
* 验证令牌有效期,相差不足20分钟,自动刷新缓存
*
* @param loginUser
* @return 令牌
*/
public void verifyToken2(LoginUser loginUser)
{
long expireTime = loginUser.getExpireTime();
long currentTime = System.currentTimeMillis();
// if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
// {
// refreshToken(loginUser);
// }
refreshToken(loginUser);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException
{
LoginUser loginUser = tokenService.getLoginUser(request);
if (Validator.isNotNull(loginUser) && Validator.isNull(SecurityUtils.getAuthentication()))
{
/********添加部分***********/
String typeString=tokenService.getType(request);
logger.error(typeString+"::::::::::::类型");
if(typeString.equals("admin")){
tokenService.verifyToken(loginUser);
}else{
tokenService.verifyToken2(loginUser);
}
/********添加部分***********/
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
chain.doFilter(request, response);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
{
/************添加部分**************/
NameHelper nameHelper= JSON.parseObject(username,NameHelper.class);
username=nameHelper.getName();
/************添加部分**************/
SysUser user = userService.selectUserByUserName(username);
if (Validator.isNull(user))
{
log.info("登录用户:{} 不存在.", username);
throw new UsernameNotFoundException("登录用户:" + username + " 不存在");
}
else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
{
log.info("登录用户:{} 已被删除.", username);
throw new BaseException("对不起,您的账号:" + username + " 已被删除");
}
else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
{
log.info("登录用户:{} 已被停用.", username);
throw new BaseException("对不起,您的账号:" + username + " 已停用");
}
return createLoginUser(user);
}
/**
* 登录校验方法
*
* @author ruoyi
*/
@Component
public class SysLoginService
{
/****************添加部分*************/
@Autowired
private HttpServletRequest request;
/****************添加部分*************/
@Autowired
private TokenService tokenService;
@Resource
private AuthenticationManager authenticationManager;
@Autowired
private RedisCache redisCache;
/**
* 登录验证
*
* @param username 用户名
* @param password 密码
* @param code 验证码
* @param uuid 唯一标识
* @return 结果
*/
public String login(String username, String password, String code, String uuid)
{
/****************添加部分*************/
String userType=request.getHeader("userType");
NameHelper nameHelper=new NameHelper();
nameHelper.setName(username);
nameHelper.setUserType(userType);
/****************添加部分*************/
String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
String captcha = redisCache.getCacheObject(verifyKey);
redisCache.deleteObject(verifyKey);
if (captcha == null)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
throw new CaptchaExpireException();
}
if (!code.equalsIgnoreCase(captcha))
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new CaptchaException();
}
// 用户验证
Authentication authentication = null;
try
{
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(JSON.toJSONString(nameHelper), password));
}
catch (Exception e)
{
if (e instanceof BadCredentialsException)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
else
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
throw new CustomException(e.getMessage());
}
}
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUser loginUser = (LoginUser) authentication.getPrincipal();
// 生成token
return tokenService.createToken(loginUser);
}
}
// request拦截器
service.interceptors.request.use(config => {
/************添加部分**************/
//添加userType标识
config.headers['userType'] = 'admin'
/************添加部分**************/
// 是否需要设置 token
const isToken = (config.headers || {}).isToken === false
if (getToken() && !isToken) {
config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
}
// get请求映射params参数
if (config.method === 'get' && config.params) {
let url = config.url + '?';
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof(value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
let params = propName + '[' + key + ']';
var subPart = encodeURIComponent(params) + "=";
url += subPart + encodeURIComponent(value[key]) + "&";
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
注意:
我用的若依新版本,引入了hutool,可能StringUtils会报错,
新版: Validator.isNull(
旧版:
StringUtils.isNull(
最后感谢若依开源这么好的框架!!!!