SpringBoot整合shiro12. SpringBoot-shiro12.1 快速入门1、导入依赖<dependencies><!-- shiro-core --><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.8.0</version></dependency><!-- configure logging --><dependency><groupId>org.slf4j</groupId><artifactId>jcl-over-slf4j</artifactId><version>1.8.0-beta0</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.8.0-beta0</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency></dependencies>2、创建log4j.properties文件log4j.rootLogger=INFO, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n# General Apache librarieslog4j.logger.org.apache=WARN# Springlog4j.logger.org.springframework=WARN# Default Shiro logginglog4j.logger.org.apache.shiro=INFO# Disable verbose logginglog4j.logger.org.apache.shiro.util.ThreadContext=WARNlog4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN3、创建shiro.ini文件[users]# user 'root' with password 'secret' and the 'admin' roleroot = secret, admin# user 'guest' with the password 'guest' and the 'guest' roleguest = guest, guest# user 'presidentskroob' with password '12345' ("That's the same combination on# my luggage!!!" ;)), and role 'president'presidentskroob = 12345, president# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'darkhelmet = ludicrousspeed, darklord, schwartz# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'lonestarr = vespa, goodguy, schwartz# -----------------------------------------------------------------------------# Roles with assigned permissions## Each line conforms to the format defined in the# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc# -----------------------------------------------------------------------------[roles]# 'admin' role has all permissions, indicated by the wildcard '*'admin = *# The 'schwartz' role can do anything (*) with any lightsaber:schwartz = lightsaber:*# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with# license plate 'eagle5' (instance specific id)goodguy = winnebago:drive:eagle54、创建Quickstart.java类import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.*;import org.apache.shiro.mgt.DefaultSecurityManager;import org.apache.shiro.realm.text.IniRealm;import org.apache.shiro.session.Session;import org.apache.shiro.subject.Subject;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * Simple Quickstart application showing how to use Shiro's API. * * @since 0.9 RC2 */public class Quickstart {private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);public static void main(String[] args) {// 已过时//Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");//SecurityManager securityManager = factory.getInstance();DefaultSecurityManager securityManager = new DefaultSecurityManager();IniRealm iniRealm = new IniRealm("classpath:shiro.ini");securityManager.setRealm(iniRealm);SecurityUtils.setSecurityManager(securityManager);// Now that a simple Shiro environment is set up, let's see what you can do:// get the currently executing user:// 获取当前的用户对象 SubjectSubject currentUser = SecurityUtils.getSubject();// Do some stuff with a Session (no need for a web or EJB container!!!)// 通过当前用户获得SessionSession session = currentUser.getSession();session.setAttribute("someKey", "aValue");String value = https://tazarkount.com/read/(String) session.getAttribute("someKey");if (value.equals("aValue")) {log.info("Subject=》session! [" + value + "]");}// let's login the current user so we can check against roles and permissions:// 判断当前的用户是否被认证if (!currentUser.isAuthenticated()) {// token : 令牌UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");token.setRememberMe(true); // 设置记住我try {currentUser.login(token);// 执行了登录操作} catch (UnknownAccountException uae) {//用户名不存在log.info("There is no user with username of " + token.getPrincipal());} catch (IncorrectCredentialsException ice) {// 密码错误log.info("Password for account " + token.getPrincipal() + " was incorrect!");} catch (LockedAccountException lae) { // 用户被锁定了log.info("The account for username " + token.getPrincipal() + " is locked." +"Please contact your administrator to unlock it.");}// ... catch more exceptions here (maybe custom ones specific to your application?catch (AuthenticationException ae) { //大异常 , 认证异常//unexpected condition?error?}}//say who they are://print their identifying principal (in this case, a username):log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");//test a role:if (currentUser.hasRole("schwartz")) {log.info("May the Schwartz be with you!");} else {log.info("Hello, mere mortal.");}//粗粒度//test a typed permission (not instance-level)if (currentUser.isPermitted("lightsaber:wield")) {log.info("You may use a lightsaber ring.Use it wisely.");} else {log.info("Sorry, lightsaber rings are for schwartz masters only.");}//细粒度//a (very powerful) Instance Level permission:if (currentUser.isPermitted("winnebago:drive:eagle5")) {log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'." +"Here are the keys - have fun!");} else {log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");}//all done - log out!//注销currentUser.logout();//结束System.exit(0);}}5、启动测试

文章插图
12.2shiro-Mybatis1、导入依赖
<dependencies><!-- thymeleaf-extras-shiro --><dependency><groupId>com.github.theborakompanioni</groupId><artifactId>thymeleaf-extras-shiro</artifactId><version>2.1.0</version></dependency><!-- lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version><scope>provided</scope></dependency><!-- 引入Mybatis mybatis-spring-boot-starter --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.0</version></dependency><!-- mysql 连接驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.27</version></dependency><!-- log4j --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><!-- druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.8</version></dependency><!--1. Subject 用户2. SecurityManager 管理所有用户3. Realm 连接数据--><!--整合shiro-spring-boot-web-starter--><dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring-boot-web-starter</artifactId><version>1.8.0</version></dependency><!-- spring-boot-starter-thymeleaf --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId><version>2.5.6</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>2、配置数据库application.yamlspring:datasource:username: rootpassword: aadzj#如果报错是时区问题 加上 serverTimezone=UTC 就OKurl: jdbc:mysql://localhost:3306/userdb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource#druid数据源专有配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置监控统计拦截的filters , stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许报错 , java.lang.ClassNotFoundException: org.apache.Log4j.Properity#则导入log4j 依赖就行filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionoProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5003、编写实体类文件路径:com--dzj--pojo--User.java@Data@NoArgsConstructor@AllArgsConstructorpublic class User {private String id;private String username;private String password;private String perms;}4、编写Mapper接口文件路径:com--dzj--mapper--UserMapper.java@Repository@Mapperpublic interface UserMapper {public User queryByUsername(String username);}5、配置全限定类别名 , 关联配置文件同样在application.yaml中配置即可# mybatis整合 全限定类别名 , 关联配置文件mybatis:type-aliases-package: com.dzj.pojomapper-locations: classpath:mapper/*.xml6、编写Mapper映射文件文件路径:resources--mapper--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.dzj.mapper.UserMapper"><select id="queryByUsername" parameterType="String" resultType="User">select * from userdb.user where username = #{username}</select></mapper>7、编写业务层【springboot配置文件 SpringBoot-shiro】接口UserService.java文件路径:com--dzj--service--UserService.java
package com.dzj.service;import com.dzj.pojo.User;public interface UserService {public User queryByUsername(String username);}接口UserService.java实现类文件路径:com--dzj--service--UserServiceImpl.java
@Servicepublic class UserServiceImpl implements UserService {@AutowiredUserMapper userMapper;@Overridepublic User queryByUsername(String username) {return userMapper.queryByUsername(username);}}8、编写controller层文件路径:com--dzj-controller--MyController.javapackage com.dzj.controller;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.authc.IncorrectCredentialsException;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.subject.Subject;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class MyController {@RequestMapping({"/","/index","/index.html"})public String toIndex(Model model){model.addAttribute("msg","helle,Shiro");return "index";}@RequestMapping("/user/add")public String add(){return "user/add";}@RequestMapping("/user/update")public String update(){return "user/update";}@RequestMapping("/toLogin")public String toLogin(){return "login";}@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";}}@RequestMapping("/noauth")@ResponseBodypublic String uauthorized(){return "未经授权无法访问此页面!";}}9、编写shiro配置类文件路径:com--dzj--config--ShiroConfig.javapackage com.dzj.config;import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;import org.apache.shiro.spring.web.ShiroFilterFactoryBean;import org.apache.shiro.web.mgt.DefaultWebSecurityManager;import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import java.util.LinkedHashMap;import java.util.Map;@Configurationpublic class ShiroConfig {// ShiroFilterFactoryBean , 步骤3@Bean(name = "shiroFilterFactoryBean")public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager")DefaultWebSecurityManager securityManager){ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();// 设置安全管理器bean.setSecurityManager(securityManager);//添加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/add","perms[user:add]");filterMap.put("/user/update","perms[user:update]");//perms只有授权了才能访问对象的页面filterMap.put("/user/*","authc");//authc主要通过了登录认证 , 就能进入根目录user//授权bean.setFilterChainDefinitionMap(filterMap);//设置登录请求认证bean.setLoginUrl("/toLogin");//未授权页面bean.setUnauthorizedUrl("/noauth");return bean;}// DefaultWebSecurityManager , 步骤2@Bean(name="defaultWebSecurityManager")public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();securityManager.setSessionManager(sessionManager());// 关联UserRealmsecurityManager.setRealm(userRealm);return securityManager;}/*在Shiro进行第一次重定向时 , 会在url后携带jsessionid , 这会导致400错误(无法找到该网页) 。解决办法:在Shiro的配置类中的sessionManager()方法中 , 将sessionIdUrlRewritingEnabled属性设置为false 。该方法返回一个DefaultWebSessionManager实例 。*/@Beanpublic DefaultWebSessionManager sessionManager() {DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();sessionManager.setSessionIdUrlRewritingEnabled(false);return sessionManager;}// 创建 Realm 对象 , 需要自定义类,步骤1@Beanpublic UserRealm userRealm(){return new UserRealm();}//整合shiroDialect:用来整合shiro 和 thymeleaf@Beanpublic ShiroDialect getShiroDialect(){return new ShiroDialect();}}编写UserRealm类文件路径:com--dzj--config--UserRealm.java
package com.dzj.config;import com.dzj.pojo.User;import com.dzj.service.UserService;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.*;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;// 自定义的 UserRealm,继承自AuthorizingRealmpublic class UserRealm extends AuthorizingRealm {@AutowiredUserService userService;// 授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("执行了=>授权doGetAuthorizationInfo");//SimpleAuthorizationInfoSimpleAuthorizationInfo info = new SimpleAuthorizationInfo();//info.addStringPermission("user:add");Subject subject = SecurityUtils.getSubject();User currentUser = (User) subject.getPrincipal();//拿到user对象//设置当前用户的权限 , 从数据库中获取info.addStringPermission(currentUser.getPerms());return info;}// 认证@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {System.out.println("执行了=>认证doGetAuthenticationInfo");UsernamePasswordToken userToken = (UsernamePasswordToken) token;// 用户名 , 密码可以数据库中取//String username = "root";//String password = "aadzj";//用户名认证//if(!userToken.getUsername().equals(username)){//return null; //自动抛出异常 , UnknownAccountException//}//连接真实的数据库User user = userService.queryByUsername(userToken.getUsername());if(user==null){return null;//返回null则自动抛出异常 , UnknownAccountException}//可以加密:MD5 MD5盐值加密//密码认证不需要我们做 , shiro做~ , 加密了return new SimpleAuthenticationInfo(user,user.getPassword(),"");}}10、前端页面index.html文件路径:resources--templates--index.html
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"><head><meta charset="UTF-8"><title>Title</title></head><body><h1>首页</h1><p th:text="${msg}"></p><shiro:guest><a th:href="https://tazarkount.com/read/@{/toLogin}">登录</a></shiro:guest><!--<div shiro:notAuthenticated><a th:href="https://tazarkount.com/read/@{/toLogin}">登录</a></div>--><hr><div shiro:hasPermission="user:add"><a th:href="https://tazarkount.com/read/@{/user/add}">add</a></div><div shiro:hasPermission="user:update"><a th:href="https://tazarkount.com/read/@{/user/update}">update</a></div></body></html>login.html文件路径:resources--templates--login.html
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="UTF-8"><title>Title</title></head><body><h1>登录</h1><hr><form th:action="@{/login}" method="get"><p>用户名:<input type="text" name="username"></p><p>密码:<input type="text" name="password"></p><p><input type="submit" value="https://tazarkount.com/read/登录"></p></form><p th:text="${msg}" style="color:red"></p></body></html>add.html文件路径:resources--templates--user--add.html
<body> <h1>add</h1></body>update.html文件路径:resources--templates--user--update.html
<body> <h1>update</h1></body>搞定 , 结束~本文来自博客园 , 作者:小公羊 , 转载请注明原文链接:https://www.cnblogs.com/aadzj/p/15636817.html
- 春季老年人吃什么养肝?土豆、米饭换着吃
- 三八妇女节节日祝福分享 三八妇女节节日语录
- 老人谨慎!选好你的“第三只脚”
- 校方进行了深刻的反思 青岛一大学生坠亡校方整改校规
- 脸皮厚的人长寿!有这特征的老人最长寿
- 长寿秘诀:记住这10大妙招 100%增寿
- 春季老年人心血管病高发 3条保命要诀
- 眼睛花不花要看四十八 老年人怎样延缓老花眼
- 香槟然能防治老年痴呆症? 一天三杯它人到90不痴呆
- 老人手抖的原因 为什么老人手会抖
