config包
ShiroConfig
点击查看代码
@Configuration
public class ShiroConfig {
// shiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
// 设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
// 添加shiro内置过滤器
/**
* anon:无需认证就可以访问
* authc:必须认证才能访问
* user:必须拥有记住我才能访问
* perms:拥有某个资源权限才能访问
* role : 拥有某个角色权限才能访问
*/
// 拦截
Map<String, String> filterMap=new HashMap<>();
// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
// 授权,未授权时候应该跳转到未授权页面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
// 设置登录请求
bean.setLoginUrl("/toLogin");
// 设置未授权请求
bean.setUnauthorizedUrl("/noauth");
return bean;
}
// DefaultWebSecurityManager
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 关联Realm
securityManager.setRealm(userRealm);
return securityManager;
}
// 创建RealM对象,需要自定义类
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
// 整合shiroDialect : 用来整合shiro 和thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
UserRealm (授权和认证)
点击查看代码
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=》授权doGetAuthorizationInfo");
// SimpleAuthorizationInfo
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
/* shrioconfig里面设置了user访问add页面需要add权限,这里给了所有add权限
info.addStringPermission("user:add");*/
// 拿到当前这个对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal(); // 拿到user对象
// 设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=》认证doGetAuthorizationInfo");
// 连接真实数据库
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
User user = userService.queryUserByName(userToken.getUsername());
if (user==null){
return null; // 用户名不匹配,抛出异常
}
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
// md5加密,MD5盐值加密
// 密码认证 shiro 做
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}