##在shiroconfig下的getShiroFilterFactoryBean类下
//授权 正常情况下,没有授权会跳到未授权页面
睿共享 filterMap.put("/user/add","perms[user:add]");睿共享 用户必须要有授权user:add才能访问
###显示一串英文显得很丑
在controller
@RequestMapping("/unauth")
@ResponseBody
public String unauthorized(){
return "未经授权无法访问此页面";
}
在ShiroConfig里面的getShiroFilterFactoryBean方法内写
//未授权页面
bean.setUnauthorizedUrl("/unauth");
登录首页点击user可以看到
##通过数据库的权限,登录时读取数据库权限,进行查询你能访问哪个资源
###拿到当前对象
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//对其进行判断perms的授权:怎么拿到当前登录的这个用户对象
Subject subject = SecurityUtils.getSubject();
//把第一个参数的user传到 授权的subject里面,subject就能拿到用户对象
User currentUser = (User)subject.getPrincipal();//拿到User对象
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());//获取用户权限
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//用户名 密码
User user = userService.queryUserByName(userToken.getUsername());
if (user==null){//沒有查到此人
return null;//会抛出异常 Unkn睿共享 ownAccount
}
Subject sub = SecurityUtils.getSubject();
Session session = sub.getSession();
session.setAttribute("loginUser",user);
//密码认证shiro做
//把第一个参数的user传到 授权的subject里面,subje睿共享 ct就能拿到用户对象
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
##导入依赖shiro-thymeleaf
<!--如果要让用户只显示自己权限相关的页面东西,需要导入shiro-thymeleaf包-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency&g睿共享 t;
###在ShiroConfig配置
//整合ShiroDialect: 用来整合shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
##login.html前端页面
<!DOCTYPE html>
<html lang="en" xmlns_th="http://www.thymeleaf.org"
xmlns_shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首頁</h1>
<p th_text="${msg}"></p>
<div th_if="${session.loginUser==null}">
<a th_href="@{/toLogin}">登录</a>
</div>
<hr>
<!--如果用户有 user:add权限就显示这个-->
<div shiro_hasPermission="user:add">
<a th_href="@{/user/add}">add</a>
</div>
<!--如果用户有 user:update权限就显示这个-->
<div shiro_hasPermission="user:update">
<a th_href="@{/user/update}">update</a>
</div>
</body>
</html>
##测试
按 李倩 权限访问只能访问 add,要是成功登录的话会把没有授权的页面给隐藏掉