org.apache.shiro
shiro-spring
1.4.0
org.apache.shiro
shiro-web
1.4.0
org.apache.shiro
shiro-core
1.4.0
org.springframework.boot
spring-boot-starter-log4j
1.3.8.RELEASE
mysql
mysql-connector-java
8.0.13
com.alibaba
druid-spring-boot-starter
1.1.9
javax.servlet
javax.servlet-api
4.0.1
provided
org.springframework.boot
spring-boot-devtools
true
true
org.springframework.boot
spring-boot-maven-plugin
org.springframework.boot
spring-boot-maven-plugin
true
package com.zhiyi.shiro.config;
import com.zhiyi.shiro.mapper.GetMapper;
import com.zhiyi.shiro.model.Shiro_User;
import com.zhiyi.shiro.model.Shiro_User_Role;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.LinkedList;
import java.util.List;
public class MyShiroRealm extends AuthorizingRealm {
private JdbcTemplate jdbcTemplate;
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private GetMapper getMapper;
@Override
public String getName() {
return “MyShiroRealm”;
}
@Override
public boolean supports(AuthenticationToken token) {
//仅支持UsernamePasswordToken类型的Token
return token instanceof UsernamePasswordToken;
}
/**
-
用于获取登录成功后的角色、权限等信息
-
@param principals
-
@return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//先通过用户名查询角色
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
Shiro_User user=(Shiro_User) (principals.getPrimaryPrincipal());//获取当前与系统交互的对象
List roles=getMapper.getUserRolesByName(user.getUserName());//通过用户名获取该用户对应的角色
//下面用于通过角色名获取对应的权限名
for (String role:roles){
List lpermissions=getMapper.getPermissionByRoleName(role);
info.addStringPermissions(lpermissions);
}
//将查询出的结果封装在权