This commit is contained in:
wuchunlei
2025-12-10 15:32:48 +08:00
commit aa5fad5c0b
41 changed files with 2222 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
package com.zmzm.financial.config;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zmzm.financial.common.entity.User;
import com.zmzm.financial.common.entity.UserToken;
import com.zmzm.financial.common.service.IUserService;
import com.zmzm.financial.common.service.IUserTokenService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class CustomRealm extends AuthorizingRealm {
@Autowired
private IUserService userService;
@Autowired
private IUserTokenService userTokenService;
@Override
public boolean supports(AuthenticationToken token) {
return token instanceof OAuth2Token;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String account = (String) principals.getPrimaryPrincipal();
User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getAccount, account));
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.addRoles(user.getRole());
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
String accessToken = token.getPrincipal().toString();
UserToken userToken = userTokenService.getOne(new LambdaQueryWrapper<UserToken>()
.eq(UserToken::getToken, accessToken));
//token失效
if(userToken == null || userToken.getExpireTime().getTime() < System.currentTimeMillis()){
throw new IncorrectCredentialsException("token失效请重新登录");
}
User user = userService.getById(userToken.getUserId());
if (user == null) throw new UnknownAccountException();
Long timeout = (userToken.getExpireTime().getTime() - System.currentTimeMillis())/(1000 * 60 * 60);
if (timeout <= 1){
// token 续期
Date now = new Date();
Date expireTime = new Date(now.getTime() + (3600 * 3 * 1000) );
userToken.setExpireTime(expireTime);
userTokenService.updateById(userToken);
}
return new SimpleAuthenticationInfo(user, token.getCredentials(), getName());
}
}