新建
This commit is contained in:
63
src/main/java/com/zmzm/financial/config/CustomRealm.java
Normal file
63
src/main/java/com/zmzm/financial/config/CustomRealm.java
Normal 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());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user