springboot整合Shiro的步骤
作者:马小欣
这篇文章主要介绍了springboot整合Shiro的步骤,帮助大家更好的理解和使用springboot框架,感兴趣的朋友可以了解下
1.创建一个springboot项目
选中web和thymeleaf
1.1新建index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>首页</h1> <p th:text="${msg}"></p> </body> </html>
1.2创建一个controller
package com.yao.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MyController { @RequestMapping({"/","/index"}) public String toIndex(Model model){ model.addAttribute("msg","hello,Shiro"); return "index"; } }
一定要记住shiro的三大对象
1.subject:用户
2.SecurityManager:管理所有用户
3.Realm:连接数据
1.3导入整合用的依赖包
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.1</version> </dependency>
1.4创建一个config(ShiroConfig),并编写他
package com.yao.config; import org.springframework.context.annotation.Configuration; @Configuration public class ShiroConfig { //ShiroFilterFactoryBean //DefaultWebSecurityManager //创建 realm 对象,这个realm对象需要自定义 }
1.5创建自己的一个realmconfig,也就是在config中创建另外一个配置类UserRealm
package com.yao.config; 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; //自定义的 UserRealm public class UserRealm extends AuthorizingRealm { //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("授权。。。"); return null; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("认证。。。"); return null; } }
1.6将UserRealm注册到ShiroConfig里面去,是我们自己写的这个类被spring托管
1.7新建两个测试页面并重新写一下index页面
add.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>add</h1> </body> </html>
update.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>update</h1> </body> </html>
index.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>首页</h1> <p th:text="${msg}"></p> <hr> <a th:href="@{/user/add}" rel="external nofollow" >add</a> | <a th:href="@{/user/update}" rel="external nofollow" >update</a> </body> </html>
1.8编写controller层
package com.yao.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MyController { @RequestMapping({"/","/index"}) public String toIndex(Model model){ model.addAttribute("msg","hello,Shiro"); return "index"; } @RequestMapping("/user/add") public String add(){ return "user/add"; } @RequestMapping("/user/update") public String update(){ return "user/update"; } }
1.9添加过滤器
还是在shiroconfig中加入:
//添加Shiro的内置过滤器 /* anon:无需认证就可以访问 authc:必须认证了才能通过 user:必须拥有记住我功能才能用 perms:拥有对某个资源的权限才可以访问 role:拥有某个角色权限才能访问 */ Map<String,String> filterMap = new LinkedHashMap<>(); // filterMap.put("/user/add","authc"); // filterMap.put("/user/update","authc"); filterMap.put("/user/*","authc"); bean.setFilterChainDefinitionMap(filterMap); //设置登录的请求 bean.setLoginUrl("/toLogin"); return bean;
这里希望没有认证就从add和update跳到login页面因此还要写一个login页面和改写controller
controller层:
@RequestMapping("/toLogin") public String toLogin(){ return "login"; }
login页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <form> <p>用户名: <input type="text" name="username"></p> <p>密码:<input type="text" name="password"></p> <p><input type="submit"></p> </form> </body> </html>
1.10上面已经完成了页面拦截的功能接下来实现用户认证的工作
login.html:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <p th:text="${msg}" ></p> <form th:action="@{/login}"> <p>用户名: <input type="text" name="username"></p> <p>密码:<input type="text" name="password"></p> <p><input type="submit"></p> </form> </body> </html>
controller:
@RequestMapping("/login") public String login(String username,String password,Model model){ //获取当前用户 Subject subject = SecurityUtils.getSubject(); //封装用户的登录数据(令牌),这里是存在全局里面,都可以调的到 UsernamePasswordToken token = new UsernamePasswordToken(username, password); try { subject.login(token);// 执行登陆的方法,如果没有异常就ok了 return "index"; } catch (UnknownAccountException e) { model.addAttribute("msg","用户名错误"); return "login"; } catch (IncorrectCredentialsException e){ model.addAttribute("msg"," 密码错误"); return "login"; } }
UserRealm:
//认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("认证。。。"); //用户名,密码 数据库中取 String name = "root"; String password = "123456"; UsernamePasswordToken userToken = (UsernamePasswordToken) token; if(!userToken.getUsername().equals(name)){ return null;//它这里会自动抛出前面的用户名错误的异常 } //密码认证不让你做,它自己做,他不让你接触密码 return new SimpleAuthenticationInfo("",password,""); } }
直接测试即可发现以上功能基本实现。
package com.yao.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MyController { @RequestMapping({"/","/index"}) public String toIndex(Model model){ model.addAttribute("msg","hello,Shiro"); return "index"; } }
2.springboot整合mybatis
2.1导入依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
2.2编写配置文件application.yml
spring: datasource: username: root password: 892095368llq #?serverTimezone=UTC解决时区的报错 url: jdbc:mysql://localhost:3306/yao?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource #Spring Boot 默认是不注入这些属性值的,需要自己绑定 #druid 数据源专有配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入 #如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
2.3编写配置文件application.properties并新建mapper文件夹
application.properties
mybatis.type-aliases-package=com.yao.pojo mybatis.mapper-locations=classpath:mapper/*.xml
2.4创建pojo层,并配置lombok
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency>
编写一个User.java
package com.yao.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private String pwd; }
2.4创建mapper层,并写出相对应的mapper接口和resources中的对应的mapper实现
UserMapper接口
package com.yao.mapper; import com.yao.pojo.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; @Repository @Mapper public interface UserMapper { public User queryUserByName(String name); } mapper。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.yao.mapper.UserMapper"> <select id="queryUserByName" parameterType="String" resultType="User"> select * from user where name = #{name} </select> </mapper>
UserService.interface
package com.yao.service; import com.yao.pojo.User; public interface UserService { public User queryUserByName(String name); } UserServiceImpl.java package com.yao.service; import com.yao.mapper.UserMapper; import com.yao.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService{ @Autowired UserMapper userMapper; @Override public User queryUserByName(String name) { return userMapper.queryUserByName(name); } }
2.6在test中测试
package com.yao; import com.yao.service.UserService; import com.yao.service.UserServiceImpl; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ShiroSpringbootApplicationTests { @Autowired UserServiceImpl userService; @Test void contextLoads() { System.out.println(userService.queryUserByName("幺幺")); } }
测试成功,继续写
2.7更改UserRealm
package com.yao.config; import com.yao.pojo.User; import com.yao.service.UserService; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; 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; //自定义的 UserRealm public class UserRealm extends AuthorizingRealm { @Autowired UserService userService; //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("授权。。。"); return null; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("认证。。。"); UsernamePasswordToken userToken = (UsernamePasswordToken) token; //连接真实数据库 User user = userService.queryUserByName(userToken.getUsername()); if (user==null){ return null; } //密码认证不让你做,它自己做,他不让你接触密码 return new SimpleAuthenticationInfo("",user.getPwd(),""); } }
2.8添加密码加密
//还有一个md5加密,集成了hashcode是不可逆的 //比如你的密码是123456 // md5(123456,32) = e10adc3949ba59abbe56e057f20f883e // md5(123456,16) = 49ba59abbe56e057 //MD5盐值加密e10adc3949ba59abbe56e057f20f883eusername //密码认证不让你做,它自己做,他不让你接触密码 return new SimpleAuthenticationInfo("",user.getPwd(),"");
2.9请求授权实现
==============
2.10绑定thymeleaf
package com.yao.mapper; import com.yao.pojo.User; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; @Repository @Mapper public interface UserMapper { public User queryUserByName(String name); }
以上就是springboot整合Shiro的步骤的详细内容,更多关于springboot整合Shiro的资料请关注脚本之家其它相关文章!