目录
三、 Spring Boot与Shiro整合实现用户认证 11
五、 Spring Boot与Shiro整合实现用户授权 33
Spring Boot整合Shiro搭建权限管理系统
- 新建一个maven工程
- 修改pom.xml文件,添加spring boot父工程
<!– 继承spring boot的默认父工程 –> <!– Spring Boot 父工程 –> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> </parent> |
- 修改默认编译的jdk版本
<!– 修改默认编译jdk版本 –> <java.version>1.8</java.version> |
- 添加spring boot启动器(web支持)
<!– web支持 –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> |
完整的pom.xml文件如下:
<project xmlns=“http://maven.apache.org/POM/4.0.0” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.hellotomcat</groupId> <artifactId>springboot-shiro</artifactId> <version>0.0.1-SNAPSHOT</version>
<!– 继承spring boot的默认父工程 –> <!– Spring Boot 父工程 –> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</version> </parent>
<dependencies> <!– web支持 –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!– thymeleaf –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
</dependencies>
<!– 修改参数 –> <properties> <!– 修改默认编译jdk版本 –> <java.version>1.8</java.version> <!– 修改thymeleaf的版本 –> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version> </properties>
</project> |
- 编写controller(UserController)
package com.hellotomcat.controller;
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
@Controller public class UserController {
/*** * 测试方法 * @return */ @RequestMapping(“/hello”) @ResponseBody // 返回json数据 public String hello() { System.out.println(“hello spring boot”); return “ok”; }
/*** * 测试thymeleaf * @param model * @return */ @RequestMapping(“/testThymeleaf”) public String testThymeleaf(Model model) { // 把数据放入model model.addAttribute(“name”, “admin”); // 返回test.html return “test”; }
}
|
- 编写启动类Application
package com.hellotomcat;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
/*** * Spring Boot启动类 * @author Lenovo * */ @SpringBootApplication public class Application {
public static void main(String[] args) { SpringApplication.run(Application.class, args); }
}
|
- 运行启动类Application(和运行普通的Java程序一样)
- 然后在浏览器输入:http://localhost:8080/hello,就可以正常访问了,出现如下画面说明启动成功
- 引入thymeleaf依赖
<!– thymeleaf –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> |
- 在controller当中添加如下方法:
/*** * 测试thymeleaf * @param model * @return */ @RequestMapping(“/testThymeleaf”) public String testThymeleaf(Model model) { // 把数据放入model model.addAttribute(“name”, “admin”); // 返回test.html return “test”; } |
- 在src/main/resources目录下面建立templates目录用来存放页面(Spting-Boot默认页面存放路径,名字不可更改)
- 在templates目录下新建test.html
<!DOCTYPE html> <html> <head> <title>测试thymeleaf的使用</title>
<meta name=“keywords” content=“keyword1,keyword2,keyword3” /> <meta name=“description” content=“this is my page” /> <meta name=“content-type” content=“text/html; charset=UTF-8”>
<!–<link rel=”stylesheet” type=”text/css” href=”./styles.css”>–>
</head>
<body> <h3 th:text=“${name}”></h3> </body> </html>
|
th:text=“${name}”为thymeleaf语法,获取model中传过来的值
- 在浏览器访问http://localhost:8080/testThymeleaf 进行测试.如果能够在页面上获取到值就说明成功了.
此处需要注意在thymeleaf3.0以前对页面标签语法要求比较严格,开始标签必须有对应的结束标签,如果没有就出现如下错误.
如果页面标签不严谨还希望使用thymeleaf的话,那就需要升级thymeleaf到3.0以上的版本,此处升级为3.0.2
- 升级thymeleaf版本(修复上面的错误),在properties节点下面添加
<!– 修改thymeleaf的版本 –> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version> |
- Shiro核心API类
Subject: 用户主体(把操作交给SecurityManager)
SecurityManager: 安全管理器(关联Realm)
Realm: shiro连接数据库的桥梁
- 导入shiro与spring整合依赖
<!– shiro与Spring整合依赖 –> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.0</version> </dependency> |
- 创建自定义Realm
package com.hellotomcat.shiro;
import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection;
/*** * 自定义Realm * @author Lenovo * */ public class UserRealm extends AuthorizingRealm{
/*** * 执行授权逻辑 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { System.out.println(“执行授权逻辑”); return null; }
/*** * 执行认证逻辑 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException { System.out.println(“执行认证逻辑”); return null; }
}
|
- 编写shiro的配置类(重点)(最基础的配置类如下)
package com.hellotomcat.shiro;
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;
/*** * Shiro的配置类 * @author Lenovo * */ @Configuration public class ShiroConfig {
/*** * 创建ShiroFilterFactoryBean */ public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier(“securityManager”)DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // 设置安全管理器 shiroFilterFactoryBean.setSecurityManager(securityManager); return shiroFilterFactoryBean; }
/*** * 创建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 getRealm() { return new UserRealm(); }
}
|
- 使用shiro内置过滤器实现拦截功能
-
- 新建两个页面add.html和update.html
add.html页面代码:
<!DOCTYPE html> <html> <head> <title>用户新增页面</title>
<meta name=“keywords” content=“keyword1,keyword2,keyword3”> <meta name=“description” content=“this is my page”> <meta name=“content-type” content=“text/html; charset=UTF-8”>
<!–<link rel=”stylesheet” type=”text/css” href=”./styles.css”>–>
</head>
<body> 用户新增 </body> </html>
|
update.html页面代码:
<!DOCTYPE html> <html> <head> <title>用户更新页面</title>
<meta name=“keywords” content=“keyword1,keyword2,keyword3”> <meta name=“description” content=“this is my page”> <meta name=“content-type” content=“text/html; charset=UTF-8”>
<!–<link rel=”stylesheet” type=”text/css” href=”./styles.css”>–>
</head>
<body> 用户更新 </body> </html>
|
-
- 修改test.html页面
<!DOCTYPE html> <html> <head> <title>测试thymeleaf的使用</title>
<meta name=“keywords” content=“keyword1,keyword2,keyword3” /> <meta name=“description” content=“this is my page” /> <meta name=“content-type” content=“text/html; charset=UTF-8”>
<!–<link rel=”stylesheet” type=”text/css” href=”./styles.css”>–>
</head>
<body> <h3 th:text=“${name}”></h3><br> 进入用户添加功能:<a href=“add”>用户添加</a><br> 进入用户更新功能:<a href=“update”>用户更新</a><br> </body> </html>
|
-
- 在UserController当中添加下面的方法
@RequestMapping(“/add”) // 没有@ResponseBody这个注释则返回页面,有就返回json数据 public String add() { return “/user/add”; }
@RequestMapping(“/update”) public String update() { return “/user/update”; } |
-
- 修改ShiroConfig类
package com.hellotomcat.shiro;
import java.util.LinkedHashMap; import java.util.Map;
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;
/*** * Shiro的配置类 * @author Lenovo * */ @Configuration public class ShiroConfig {
/*** * 创建ShiroFilterFactoryBean */ @Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier(“securityManager”)DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // 设置安全管理器 shiroFilterFactoryBean.setSecurityManager(securityManager);
// 添加Shiro内置过滤器 /*** * Shiro内置过滤器,可以实现权限相关的拦截 * 常用的过滤器: * anon: 无需认证(登录)可以访问 * authc: 必须认证才可以访问 * user: 如果使用rememberMe的功能可以直接访问 * perms: 该资源必须得到资源权限才可以访问 * role: 该资源必须得到角色权限才可以访问 */ Map<String, String> filterMap = new LinkedHashMap<String, String>();
filterMap.put(“/add”, “authc”); filterMap.put(“/update”, “authc”);
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
return shiroFilterFactoryBean; }
/*** * 创建DefaultWebSecurityManager */ @Bean(name=“securityManager”) public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier(“userRealm”)UserRealm userRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 关联realm securityManager.setRealm(userRealm); return securityManager; }
/*** * 创建Realm */ @Bean(name=“userRealm”) public UserRealm getRealm() { return new UserRealm(); }
}
|
-
- 验证拦截功能,在test页面点击超链接,如果出现以下情况,说明拦截成功
-
- 设置跳转到自定义登录页面
- 新建一个登录页面login.html
- 设置跳转到自定义登录页面
login.html代码如下:
<!DOCTYPE html> <html> <head> <title>登录页面</title>
<meta name=“keywords” content=“keyword1,keyword2,keyword3”> <meta name=“description” content=“this is my page”> <meta name=“content-type” content=“text/html; charset=UTF-8”>
<!–<link rel=”stylesheet” type=”text/css” href=”./styles.css”>–>
</head>
<body> 登录页面 <br> </body> </html>
|
-
-
- 在UserController当中添加如下方法:
-
@RequestMapping(“/toLogin”) public String toLogin() { return “/login”; } |
-
-
- 修改ShiroConfig类
-
package com.hellotomcat.shiro;
import java.util.LinkedHashMap; import java.util.Map;
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;
/*** * Shiro的配置类 * @author Lenovo * */ @Configuration public class ShiroConfig {
/*** * 创建ShiroFilterFactoryBean */ @Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier(“securityManager”)DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); // 设置安全管理器 shiroFilterFactoryBean.setSecurityManager(securityManager);
// 添加Shiro内置过滤器 /*** * Shiro内置过滤器,可以实现权限相关的拦截 * 常用的过滤器: * anon: 无需认证(登录)可以访问 * authc: 必须认证才可以访问 * user: 如果使用rememberMe的功能可以直接访问 * perms: 该资源必须得到资源权限才可以访问 * role: 该资源必须得到角色权限才可以访问 */ Map<String, String> filterMap = new LinkedHashMap<String, String>();
filterMap.put(“/add”, “authc”); filterMap.put(“/update”, “authc”);
// 修改默认的登录页面 shiroFilterFactoryBean.setLoginUrl(“/toLogin”);
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
return shiroFilterFactoryBean; }
/*** * 创建DefaultWebSecurityManager */ @Bean(name=“securityManager”) public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier(“userRealm”)UserRealm userRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 关联realm securityManager.setRealm(userRealm); return securityManager; }
/*** * 创建Realm */ @Bean(name=“userRealm”) public UserRealm getRealm() { return new UserRealm(); }
}
|
-
-
- 验证,如果页面调整到自定义登录页面则成功
-
-
- 使用通配符简化配置,修改ShiroConfig类
将
filterMap.put(“/add”, “authc”); filterMap.put(“/update”, “authc”); |
修改为:
filterMap.put(“/testThymeleaf”, “anon”); filterMap.put(“/*”, “authc”); //此句必须放在最下面,否则将会对所有的请求进行拦截,导致不需登录也可以访问的配置均无效 |
- 实现用户验证(登录)操作
-
- 修改登录页面login.html
<!DOCTYPE html> <html> <head> <title>登录页面</title>
<meta name=“keywords” content=“keyword1,keyword2,keyword3”> <meta name=“description” content=“this is my page”> <meta name=“content-type” content=“text/html; charset=UTF-8”>
<!–<link rel=”stylesheet” type=”text/css” href=”./styles.css”>–>
</head>
<body> <h3>登录</h3> <h5 th:text=“${msg}” style=”color: red“></h5> <form action=“login” method=“post”> 用户名:<input type=“text” name=“name”/><br> 密码: <input type=“password” name=“password”/><br> <input type=“submit” value=“登录”/> </form> </body> </html>
|
-
- 在controller当中添加方法
/*** * 登录逻辑处理 */ @RequestMapping(“/login”) public String login(String name, String password,Model model) { /*** * 使用Shiro编写认证操作 */ // 1.获取Subject Subject subject = SecurityUtils.getSubject();
// 2.封装用户数据 UsernamePasswordToken token = new UsernamePasswordToken(name, password);
// 3.执行登录方法 try { subject.login(token); // 没有异常则说明登录成功 return “redirect:/testThymeleaf”; } catch (UnknownAccountException e) { //e.printStackTrace(); // 登录失败:用户名不存在 model.addAttribute(“msg”, “用户名不存在”); return “login”; } catch (IncorrectCredentialsException e) { //e.printStackTrace(); // 登录失败:密码错误 model.addAttribute(“msg”, “密码错误”); return “login”; } } |
-
- 在ShiroConfig当中添加如下代码,放行登录操作
filterMap.put(“/login”, “anon”); // 放行登录操作 |
-
- 编写UserRealm的认证(判断)逻辑
/*** * 执行认证逻辑 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println(“执行认证逻辑”);
// 假设数据库的用户名和密码 String name = “admin”; String password = “root”;
// 编写shiro判断逻辑,判断用户名和密码是否正确 // 1.判断用户名 UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken; if (!token.getUsername().equals(name)) { // 用户名不存在 return null; // 返回null时,shiro底层会抛出UnknowAccountException }
// 2.判断密码 return new SimpleAuthenticationInfo(“”, password, “”); } |
- 导入Mybatis相关依赖,修改pom.xml文件
<!– 导入mybatis相关的依赖 –> <!– 数据库连接池 druid–> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> <!– mysql驱动 –> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!– SpringBoot的mybatis启动器 –> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> |
- 新建一个数据库,然后再新建一张数据库表,建表语句如下(数据库需要手动创建):
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
- 在src/main/resources目录下面新建application.properties。(位置和文件名固定)
spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/db_springboot spring.datasource.username=root spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
mybatis.type-aliases-package=com.hellotomcat.domain |
- 编写实体类User
package com.hellotomcat.domain;
public class User {
private Integer id; private String name; private String password; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return “User [id=” + id + “, name=” + name + “, password=” + password + “]”; }
}
|
- 编写查询接口
package com.hellotomcat.mapper;
import com.hellotomcat.domain.User;
public interface UserMapper {
public User findByName(String name);
}
|
- 编写UserMapper.xml映射文件
<?xml version=“1.0” encoding=“UTF-8” ?> <!DOCTYPE mapper PUBLIC “-//mybatis.org//DTD Mapper 3.0//EN” “http://mybatis.org/dtd/mybatis-3-mapper.dtd”> <mapper namespace=“com.hellotomcat.mapper.UserMapper”>
<select id=“findByName” parameterType=“string” resultType=“user”> SELECT id, NAME, PASSWORD FROM `user` where name=#{value} </select>
</mapper>
|
- 编写业务接口和实现
接口:
package com.hellotomcat.service;
import com.hellotomcat.domain.User;
public interface UserService {
public User findByName(String name);
}
|
实现:
package com.hellotomcat.service.impl;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
import com.hellotomcat.domain.User; import com.hellotomcat.mapper.UserMapper; import com.hellotomcat.service.UserService;
@Service public class UserServiceImpl implements UserService{
// 注入mapper接口 @Autowired private UserMapper userMapper;
@Override public User findByName(String name) { return userMapper.findByName(name); }
}
|
- 在启动类Application当中添加mapper包扫描的注释
package com.hellotomcat;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
/*** * Spring Boot启动类 * @author Lenovo * */ @SpringBootApplication @MapperScan(“com.hellotomcat.mapper”) public class Application {
public static void main(String[] args) { SpringApplication.run(Application.class, args); }
}
|
- 修改UserRealm的认证逻辑
// 注入用户操作接口 @Autowired private UserService userService; /*** * 执行认证逻辑 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println(“执行认证逻辑”);
// 编写shiro判断逻辑,判断用户名和密码是否正确 // 1.判断用户名 UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
User user = userService.findByName(token.getUsername());
if (user == null) { // 用户名不存在 return null; // 返回null时,shiro底层会抛出UnknowAccountException }
// 2.判断密码 return new SimpleAuthenticationInfo(“”, user.getPassword(), “”); } |
- 使用shiro内置过滤器实现资源拦截
- 修改ShiroConfig,在过滤器当中添加资源过滤器
// 授权过滤器perms[user:add]方括号中的可以自定义。注意:当前授权拦截后,shiro会自动跳转到未授权页面 filterMap.put(“/add”, “perms[user:add]”); |
-
- 在浏览器访问用户添加功能,如果出现如下页面,则表示拦截成功(此为shiro自动跳转到的页面,因为没有对应的页面显示,所以就显示错误页面)
-
- 自定义未授权提示页面
- 新建未授权提示noAuth.html页面
- 自定义未授权提示页面
<!DOCTYPE html> <html> <head> <title>未授权提示页面</title>
<meta name=“keywords” content=“keyword1,keyword2,keyword3”> <meta name=“description” content=“this is my page”> <meta name=“content-type” content=“text/html; charset=UTF-8”>
<!–<link rel=”stylesheet” type=”text/css” href=”./styles.css”>–>
</head>
<body> 亲,您未经授权访问该页面 </body> </html>
|
-
-
- 修改ShiroConfig类
// 设置未授权提示页面 shiroFilterFactoryBean.setUnauthorizedUrl(“/noAuth”); |
-
-
- 在UserController当中添加如下方法:
-
/*** * 跳转到未授权提示页面 */ @RequestMapping(“/noAuth”) public String noAuth() { return “/noAuth”; } |
-
-
- 如果浏览器在未授权的情况下跳转到自定义页面说明修改成功
- 修改UserRealm完成Shiro的资源授权
/*** * 执行授权逻辑 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { System.out.println(“执行授权逻辑”);
// 给资源进行授权 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 添加资源的授权字符串(必须和下面的资源拦截器当中的自定义字符串一致) info.addStringPermission(“user:add”);
return info; } |
- 连接数据库实现资源动态授权
-
- 修改数据库表
ALTER TABLE `db_springboot`.`user` ADD COLUMN `perms` varchar(50) NULL AFTER `password`; |
-
- 修改实体类User
package com.hellotomcat.domain;
public class User {
private Integer id; private String name; private String password; private String perms; public String getPerms() { return perms; } public void setPerms(String perms) { this.perms = perms; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return “User [id=” + id + “, name=” + name + “, password=” + password + “]”; }
}
|
-
- 修改UserMapper接口,添加方法
public User findById(Integer id); |
-
- 在业务接口和实现类中添加方法
接口:
public User findById(Integer id); |
实现类:
@Override public User findById(Integer id) { return userMapper.findById(id); } |
-
- 修改UserRealm中的方法
package com.hellotomcat.shiro;
import org.apache.shiro.SecurityUtils; 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.authc.UsernamePasswordToken; 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.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired;
import com.hellotomcat.domain.User; import com.hellotomcat.service.UserService;
/*** * 自定义Realm * @author Lenovo * */ public class UserRealm extends AuthorizingRealm{
/*** * 执行授权逻辑 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) { System.out.println(“执行授权逻辑”);
// 给资源进行授权 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 添加资源的授权字符串(必须和下面的资源拦截器当中的自定义字符串一致) //info.addStringPermission(“user:add”);
// 到数据库查询当前登录用户的授权字符串 // 获取当前登录用户 Subject subject = SecurityUtils.getSubject(); User user = (User)subject.getPrincipal();
User dbUser = userService.findById(user.getId()); info.addStringPermission(dbUser.getPerms());
return info; }
// 注入用户操作接口 @Autowired private UserService userService; /*** * 执行认证逻辑 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println(“执行认证逻辑”);
// 编写shiro判断逻辑,判断用户名和密码是否正确 // 1.判断用户名 UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
User user = userService.findByName(token.getUsername());
if (user == null) { // 用户名不存在 return null; // 返回null时,shiro底层会抛出UnknowAccountException }
// 2.判断密码 return new SimpleAuthenticationInfo(user, user.getPassword(), “”); }
}
|
-
- 在ShiroConfig当中新增拦截项
filterMap.put(“/update”, “perms[user:update]”); |
- 导入thymeleaf扩展依赖,修改pom.xml文件
<!– thymeleaf对shiro的扩展依赖 –> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency> |
- 在ShiroConfig当中配置ShiroDialect
/*** * 配置ShiroDialect,用于thymeleaf和shiro标签配合使用 */ @Bean public ShiroDialect getShiroDialect() { return new ShiroDialect(); } |
- 在页面当中使用shiro标签控制资源显示,修改test.html页面
<!DOCTYPE html> <html> <head> <title>测试thymeleaf的使用</title>
<meta name=“keywords” content=“keyword1,keyword2,keyword3” /> <meta name=“description” content=“this is my page” /> <meta name=“content-type” content=“text/html; charset=UTF-8”>
<!–<link rel=”stylesheet” type=”text/css” href=”./styles.css”>–>
</head>
<body> <h3 th:text=“${name}”></h3><br> <hr> <div shiro:hasPermission=“user:add”> 进入用户添加功能:<a href=“add”>用户添加</a><br> </div> <div shiro:hasPermission=“user:update”> 进入用户更新功能:<a href=“update”>用户更新</a><br> </div> </body> </html>
|
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/111137.html