1.config的配置
package com.li.myspringboot.shiroall.shiro;
import com.li.myspringboot.shiroall.entity.Authority;
import com.li.myspringboot.shiroall.service.AuthorityService;
import com.li.myspringboot.shiroall.service.RarsService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
import java.util.*;
//shiro的相关的配置类 配置文件
@Configuration
public class ShiroConfig {
@Resource
private RarsService rarsService;
@Resource
private AuthorityService authorityService;
//创建安全过滤器
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
//添加shiro内置的过滤拦截器
/**
* shiro内置过滤器拦截
* 常用的过滤器有
* anon:无需认证(登录)可以访问
* authc:必须认证car可以访问
* user:如果使用rememberMe的功能可以直接访问
* perms:该资源必须得到资源权限才可以访问
* role:该资源必须得到角色的权限才可以访问
*/
Map<String,String> filterMap = new LinkedHashMap<String,String>();
//无需认证即可访问
filterMap.put("/static/**", "anon");
filterMap.put("/user/login","anon");
filterMap.put("/authority/**","anon");
filterMap.put("/logout", "logout");
filterMap.put("/user/**", "roles[用户管理员]");
filterMap.put("/stock/**", "roles[订单管理员]");
filterMap.put("/order/**", "roles[库存管理员]");
//filterMap.put("用户管理", "/user/** ,/order/**");
// filterMap.put("/user/**", "roles[admin,user]");
// filterMap.put("/用户/**", "roles[admin]");
// //进行动态权限的拦截
// //查询角色对应的权限信息
// List<Map> roleFun = authorityService.finRoleFun();
// Map<String,StringBuffer> funMap = new HashMap<String,StringBuffer>();
// for (Map map:roleFun) {
// //获取角色相关信息
// String roleName = map.get("role_name").toString();
// //获取权限相关信息
// String authFun = map.get("auth_fun").toString();
// boolean isContain = funMap.containsKey(authFun);
// //如果不包含此权限信息
// if(!isContain){
// StringBuffer sBuffer = new StringBuffer();
// sBuffer.append(roleName);
// funMap.put(authFun,sBuffer);
// }else{
//
// StringBuffer sBuffer= funMap.get(authFun);
// //roles[roles.length]
// sBuffer.append(",");
// sBuffer.append(roleName);
// funMap.put(authFun,sBuffer);
// }
// }\
//查找角色对应菜单信息进行动态权限的拦截
// List<Map> roleFun = authorityService.findAllRoleFun();
// for (Map rolefun:roleFun) {
// //实现真正的动态授权
// //System.err.println((String) rolefun.get("auth_fun")+"========="+"roles["+rolefun.get("role_name")+"]");
// filterMap.put((String) rolefun.get("auth_fun"),"roles["+rolefun.get("role_name")+"]");
// }
//首先在前台页面的权限进行展示
//在对相关的权限信息进行拦截
//filterMap.put("/user/**", "roles[liyanming]");
filterMap.put("/**","authc");
//拦截所有请求
//filterMap.put("/*","authc");
//修改没有权限所要返回的登录页面的信息
//shiroFilterFactoryBean.setLoginUrl("/toLogin");
//将自定义的所需权限的拦截 放入创建的安全过滤器
//角色过滤器
/*List<Map<String,Object>> list = rarsService.selectAll();
for(Map map :list){
String authFun = map.get("auth_fun").toString();
String roleName = map.get("role_name").toString();
filterMap.put(authFun,"roles["+roleName+"]");
}*/
// filterMap.put("/user","roles[超级管理员,高级管理员,普通管理员]");
// filterMap.put("/order","roles[超级管理员,高级管理员]");
// filterMap.put("/stock","roles[超级管理员]");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
return shiroFilterFactoryBean;
}
//创建defaultWebSecurityManger
//Qualifier将spring环境中的UserRealm注入到定义的userRealm
@Bean(name="securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(userRealm);
return defaultWebSecurityManager;
}
//创建Realm
//@Bean将创建的bean放入到Spring环境中去
@Bean("userRealm")
public UserRealm getRealm(@Qualifier("hashedCredentialsMatcher") HashedCredentialsMatcher matcher){
UserRealm userRealm = new UserRealm();
userRealm.setCredentialsMatcher(matcher);
return userRealm;
}
//这个类是为了对密码进行编码的,防止数据库里面明码保存
@Bean("hashedCredentialsMatcher")
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//指定密码加密的方式
hashedCredentialsMatcher.setHashAlgorithmName("MD5");
//指定加密的次数
hashedCredentialsMatcher.setHashIterations(1024);
hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
return hashedCredentialsMatcher;
}
}
2.realm的配置
package com.li.myspringboot.shiroall.shiro;
import com.li.myspringboot.shiroall.entity.Role;
import com.li.myspringboot.shiroall.entity.User;
import com.li.myspringboot.shiroall.service.AuthorityService;
import com.li.myspringboot.shiroall.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
public class UserRealm extends AuthorizingRealm {
@Resource
private UserService userService;
@Resource
private AuthorityService authorityService;
//此方法用于执行授权逻辑
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行授权逻辑");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo ();
//获取前端输入的用户信息,封装成user对象
User user = (User)principals.getPrimaryPrincipal();
String userName = user.getUserName();
//创建一个Collection集合用于存放相关的权限信息
Collection<String> rolesCollection = new HashSet<String>();
//Collection<String> funsCollection = new HashSet<String>();
// funsCollection.add("/user/findAllUser");
//通过用户名查找用户的权限信息
List<Role> roleList = authorityService.findRoleByName(userName);
//info.addStringPermission("/user/findAllUser");
for (Role role: roleList) {
rolesCollection.add(role.getRoleName());
// System.err.println("========"+role.getRoleName());
}
info.addRoles(rolesCollection);
return info;
}
//此方法用于执行认证逻辑
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行认证逻辑");
//通过token获取用户名和密码
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;
//获取登录的用户名
String loginUname = usernamePasswordToken.getUsername();
//根据用户名查询用户信息
User user = userService.findByUserName(loginUname);
if(user == null){
//用户不存在 shiro底层对抛出UnKnowAccountException
return null;
}
//盐值为登录名
ByteSource bytes = ByteSource.Util.bytes(loginUname);
//将数据库中取出的秘密进行md5加密并加1024次 1.加密的方式 2.用户的密码 3.盐值 4加密的次数
Object upwd = new SimpleHash("MD5",user.getUserPwd(),ByteSource.Util.bytes(user.getUserName()),1024);
//4个参数 1.为返回login的一些参数 2.密码 3.盐值 4.当前realm的name
AuthenticationInfo info = new SimpleAuthenticationInfo(user,upwd,bytes,getName());
return info;
}
}
3.为登录验证的使用
@RequestMapping("/checklogin") @ResponseBody public Map checklogin(String username , String pwd ){ Map map = new HashMap(); //1.获取subject对象 Subject subject = SecurityUtils.getSubject(); //2.封装用户数据 UsernamePasswordToken tocken = new UsernamePasswordToken(username,pwd); //3.执行登录方法 /** * 没有异常代表登录成功 */ try { subject.login(tocken); map.put("code",0); map.put("msg","登录成功"); //验证成功后所要跳转的页面 map.put("jump","/iemes/list"); }catch(UnknownAccountException e){ //用户信息不存在 map.put("code",1); map.put("msg","用户信息不存在"); }catch (IncorrectCredentialsException e){ //密码错误 map.put("code",1); map.put("msg","密码错误"); } return map; }