目录
Shiro是一个对用户登录与访问权限进行校验的框架,可以方便地与Spring进行集成。本文讲解如何使用Shiro进行登录和权限校验,因为项目中需要获取所有活跃的session,使用了SessionDAO来存储session。
maven依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.13.0</version>
</dependency>
<!-- shiro 整合sping -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.13.0</version>
</dependency>
代码配置
AuthorizingRealm
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.digitelectric.network_manage.entity.po.User;
import com.digitelectric.network_manage.mapper.UserMapper;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CustomRealm extends AuthorizingRealm {
@Resource
UserMapper userMapper;
@Resource
ValueOperations<String, String> valueOperations;
@Resource
RedisTemplate redisTemplate;
@Resource
SessionDAO sessionDAO;
@Value("${shiro.session-timeout}")
private Long timeout;
//获取当前用户的权限
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String token = (String) principals.getPrimaryPrincipal();
String userStr = valueOperations.get(token);
if (StringUtils.isBlank(userStr)) {
throw new AccountException("登录失效,请重新登录");
}
User user = JSONObject.parseObject(userStr, User.class);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(Sets.newHashSet(user.getRole()));
return info;
}
//登录
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String name = (String) authenticationToken.getPrincipal();
String password = new String((char[]) authenticationToken.getCredentials());
User user &