1,建立springboot项目
2,pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- jsp依赖-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>9.0.35</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!-- shiro与springboot整合依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.5.3</version>
</dependency>
<!-- mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.19</version>
</dependency>
<!-- shiro整合ehcache 做缓存-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.5.3</version>
</dependency>
<!-- 整合redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
3,建立三个jsp文件(index,login,regis)
index
<%@ page pageEncoding="UTF-8" %>
<%--引入shiro标签--%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html lang="en">
<body>
<h2>系统主页</h2>
<a href="${pageContext.request.contextPath}/user/logout">退出</a>
<ul>
<shiro:hasAnyRoles name="user,admin">
<li><a href="">用户管理</a>
<ul>
<shiro:hasPermission name="user:add:*">
<li href="">添加</li>
</shiro:hasPermission>
<shiro:hasPermission name="user:delete:*">
<li href="">删除</li>
</shiro:hasPermission>
<shiro:hasPermission name="user:update:*">
<li href="">修改</li>
</shiro:hasPermission>
<shiro:hasPermission name="user:find:*">
<li href="">查询</li>
</shiro:hasPermission>
</ul>
</li>
</shiro:hasAnyRoles>
<shiro:hasRole name="admin">
<li><a href="">商品管理</a></li>
<li><a href="">订单管理</a></li>
<li><a href="">物流管理</a></li>
</shiro:hasRole>
</ul>
</body>
</html>
login.jsp
<%@ page pageEncoding="UTF-8" %>
<%--<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>--%>
<html lang="en">
<body>
<h1>用户登录</h1>
<form action="${pageContext.request.contextPath}/user/login"method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="text" name="password"><br/>
<input type="submit" value="登录">
<a href="register.jsp"><input value="立即注册"></a>
</form>
</body>
</html>
register.jsp
<%@ page pageEncoding="UTF-8" %>
<%--<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>--%>
<html lang="en">
<body>
<h1>用户注册</h1>
<form action="${pageContext.request.contextPath}/user/register"method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="text" name="password"><br/>
<input type="submit" value="注册">
</form>
</body>
</html>
4,applcation文件
server.port=8888
server.servlet.context-path=/shiro
spring.application.name=shiro
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
spring.datasource.type=com.alibaba.druid.pool.DruidDataSourceC3P0Adapter
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/cloud?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
mybatis.type-aliases-package=com.shiro.springboot_jsp_shiro.entity
mybatis.mapper-locations=classpath:com/shiro/mapper/*.xml
logging.level.com.shiro.springboot_jsp_shiro.dao=debug
spring.redis.port=6379
spring.redis.host=localhost
spring.redis.database=0
5,主启动类
@SpringBootApplication
public class SpringbootJspShiroApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootJspShiroApplication.class, args);
}
}
6,先建立两个工具类
SaltUtils(用来获取盐)
package com.shiro.springboot_jsp_shiro.utils;
import java.util.Random;
public class SaltUtils {
public static String getSalt(int n){
char [] chars ="abcdefghigkfnABCDEFGHIGKFN".toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0;i < n ;i++){
char aChar = chars[new Random().nextInt(chars.length)];
stringBuilder.append(aChar);
}
return stringBuilder.toString();
}
public static void main(String[] args) {
System.out.println(getSalt(4));
}
ApplicationContextUtils(用来动态获取bean工厂)
package com.shiro.springboot_jsp_shiro.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
//根据bean的名字获取工厂中指定的bean
public static Object getBean(String beanName){
return context.getBean(beanName);
}
}
7,建立ShiroConfig用来做请求拦截判断
在这里插入代码片package com.shiro.springboot_jsp_shiro.config;
import com.shiro.springboot_jsp_shiro.shiro.realms.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
//用来整合shiro框架要用的类
@Configuration
public class ShiroConfig {
//创建shiroFilter,负责拦截所有请求
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//给filter设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
//配置系统受限资源,设置公共资源
Map<String,String> map = new HashMap<>();
map.put("/user/login","anon");//anon设置为公共资源
map.put("/**","authc");//authc请求这个资源需要授权,认证
map.put("/register.jsp","anon");
map.put("/user/register","anon");
//默认认证界面路径
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
//创建安全管理器
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//给安全管理器设置
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
//创建自定义realm
@Bean
public Realm getRealm(){
CustomerRealm customerRealm = new CustomerRealm();
//修改凭证校验匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName("Md5");
credentialsMatcher.setHashIterations(1024); //设置散列
customerRealm.setCredentialsMatcher(credentialsMatcher);
//开启缓存管理(如果突然断电丢失)
customerRealm.setCacheManager(new EhCacheManager());
//开启全局缓存管理
customerRealm.setCachingEnabled(true);
//开启认证缓存
customerRealm.setAuthenticationCachingEnabled(true);
//给缓存起名字
customerRealm.setAuthenticationCacheName("authentictionCache");
//开启授权缓存
customerRealm.setAuthorizationCachingEnabled(true);
customerRealm.setAuthorizationCacheName("authorizationCache");
return customerRealm;
}
}
8,自定义realm(CustomerRealm)
package com.shiro.springboot_jsp_shiro.shiro.realms;
import com.shiro.springboot_jsp_shiro.entity.Perms;
import com.shiro.springboot_jsp_shiro.entity.Role;
import com.shiro.springboot_jsp_shiro.entity.User;
import com.shiro.springboot_jsp_shiro.service.UserService;
import com.shiro.springboot_jsp_shiro.utils.ApplicationContextUtils;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import java.util.List;
//自定义realm
public class CustomerRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//获取身份信息
String primaryPrincipal = (String)principals.getPrimaryPrincipal();
//根据身份信息获取角色和权限信息
UserService userService = (UserService)ApplicationContextUtils.getBean("userSerivce");
User user = userService.findRolesByUserName(primaryPrincipal);
if(!CollectionUtils.isEmpty(user.getRoles())){
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
user.getRoles().forEach(role -> {
simpleAuthorizationInfo.addRole(role.getName());
//权限信息
List<Perms> perms = userService.findPermsByRoleId(role.getId());
if(!CollectionUtils.isEmpty(perms)){
perms.forEach(perm-> {
System.out.println("getName+++"+perm.getName());
simpleAuthorizationInfo.addStringPermission(perm.getName());
});
}
});
return simpleAuthorizationInfo;
}
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//获取身份信息
String principal = (String)token.getPrincipal();
//在工厂中获取service对象
UserService userService = (UserService)ApplicationContextUtils.getBean("userSerivce");
User user = userService.findByUserName(principal);
if(!ObjectUtils.isEmpty(user)){
return new SimpleAuthenticationInfo(
user.getUsername(),
user.getPassword(),
ByteSource.Util.bytes(user.getSalf()),
this.getName());
}
return null;
}
}
9,建立数据库
DROP TABLE IF EXISTS `t_pers`;
CREATE TABLE `t_pers` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`name` varchar(80) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`name` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `t_role_perms`;
CREATE TABLE `t_role_perms` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`roieid` int(6) DEFAULT NULL,
`permsid` int(6) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`username` varchar(40) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`salf` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
insert into `t_user`(`id`,`username`,`password`,`salf`) values (1,'linailong','4227778d19f0a6003da150dc7ae6d3c6','gFhfdAca'),(4,'liujuan','2c4b26e3b7d566416e4493181137a68c','hFGfGGgN');
DROP TABLE IF EXISTS `t_user_role`;
CREATE TABLE `t_user_role` (
`id` int(6) NOT NULL AUTO_INCREMENT,
`userid` int(6) DEFAULT NULL,
`roleid` int(6) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
10,建立三个实体类perms,Role,User
Perms
package com.shiro.springboot_jsp_shiro.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Perms {
private Integer id;
private String name;
private String url;
}
Role
package com.shiro.springboot_jsp_shiro.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.List;
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Role {
private Integer id;
private String name;
//定义权限集合
private List <Perms> perms;
}
User
package com.shiro.springboot_jsp_shiro.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.util.List;
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String username;
private String password;
private String salf;
//定义角色集合
private List <Role> roles;
}
11,建立DAO UserDao
package com.shiro.springboot_jsp_shiro.dao;
import com.shiro.springboot_jsp_shiro.entity.Perms;
import com.shiro.springboot_jsp_shiro.entity.Role;
import com.shiro.springboot_jsp_shiro.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserDao {
void save(User user);
User findByUserName(String username);
//根据用户名查询所有角色
User findRolesByUserName(String username);
//根据角色id查询权限集合
List<Perms> findPermsByRoleId(Integer id);
}
12,建立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.shiro.springboot_jsp_shiro.dao.UserDao">
<insert id="save" parameterType="com.shiro.springboot_jsp_shiro.entity.User" useGeneratedKeys="true" keyProperty="id">
insert into t_user value (#{id},#{username},#{password},#{salt})
</insert>
<select id="findByUserName" parameterType="java.lang.String" resultType="com.shiro.springboot_jsp_shiro.entity.User">
select id,username,password,salf from t_user where username= #{username}
</select>
<select id="findRolesByUserName" parameterType="java.lang.String" resultMap="userMap">
SELECT
u.id uid,u.username,r.id, r.name rname
FROM t_user u
LEFT JOIN t_user_role ur
ON u.id=ur.userid
LEFT JOIN t_role r
ON ur.roleid = r.id
WHERE u.username=#{username}
</select>
<resultMap id="userMap" type="com.shiro.springboot_jsp_shiro.entity.User">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<collection property="roles" javaType="list" ofType="com.shiro.springboot_jsp_shiro.entity.Role">
<id column="id" property="id"/>
<result column="rname" property="name"/>
</collection>
</resultMap>
<select id="findPermsByRoleId" parameterType="java.lang.Integer" resultType="com.shiro.springboot_jsp_shiro.entity.Perms">
SELECT p.id,p.name,p.`url`,r.name FROM t_role r
LEFT JOIN t_role_perms rp
ON r.id = rp.`roieid`
LEFT JOIN t_perms p
ON rp.`permsid`=p.`id`
WHERE r.id=#{id}
</select>
</mapper>
13,建立service和serviceImpl
UserService
package com.shiro.springboot_jsp_shiro.service;
import com.shiro.springboot_jsp_shiro.entity.Perms;
import com.shiro.springboot_jsp_shiro.entity.Role;
import com.shiro.springboot_jsp_shiro.entity.User;
import java.util.List;
public interface UserService {
void register(User user);
User findByUserName(String username);
User findRolesByUserName(String username);
List<Perms> findPermsByRoleId(Integer id);
}
UserSerivceImpl
package com.shiro.springboot_jsp_shiro.service.Impl;
import com.shiro.springboot_jsp_shiro.dao.UserDao;
import com.shiro.springboot_jsp_shiro.entity.Perms;
import com.shiro.springboot_jsp_shiro.entity.Role;
import com.shiro.springboot_jsp_shiro.entity.User;
import com.shiro.springboot_jsp_shiro.service.UserService;
import com.shiro.springboot_jsp_shiro.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service("userSerivce")
@Transactional
public class UserSerivceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void register(User user) {
String salt = SaltUtils.getSalt(8);
user.setSalf(salt);
Md5Hash md5Hash = new Md5Hash(user.getPassword(),salt,1024);
user.setPassword(md5Hash.toHex());
userDao.save(user);
}
@Override
public User findByUserName(String username) {
return userDao.findByUserName(username);
}
@Override
public User findRolesByUserName(String username) {
return userDao.findRolesByUserName(username);
}
@Override
public List<Perms> findPermsByRoleId(Integer id) {
return userDao.findPermsByRoleId(id);
}
}
14,建立两个Controller
UserController
package com.shiro.springboot_jsp_shiro.controller;
import com.shiro.springboot_jsp_shiro.entity.User;
import com.shiro.springboot_jsp_shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 身份认证
* @param username
* @param password
* @return
*/
@RequestMapping("/login")
public String login(String username,String password){
//获取主题对象
Subject subject = SecurityUtils.getSubject();
try {
subject.login(new UsernamePasswordToken(username,password));
return "redirect:/index.jsp";
} catch (UnknownAccountException e) {
e.printStackTrace();
System.out.println("用户名错误");
}catch (IncorrectCredentialsException e){
e.printStackTrace();
System.out.println("密码错误");
}
return "redirect:/login.jsp";
}
/**
* 退出登录
*/
@RequestMapping("/logout")
public String logout(){
Subject subject = SecurityUtils.getSubject();
subject.logout();//退出登录
return "redirect:/login.jsp";
}
/**
* 用户认证
*/
@RequestMapping("register")
public String register(User user){
try {
userService.register(user);
return "redirect:/login.jsp";
} catch (Exception e) {
e.printStackTrace();
return "redirect:/register.jsp";
}
}
}
OrderController
package com.shiro.springboot_jsp_shiro.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//在代码中完成授权操作
@Controller
@RequestMapping("/order")
public class OrderController {
@RequestMapping("/save")
// @RequiresRoles(value = {"admin","user"})//用来判断角色,同时具有admin和user
// @RequiresPermissions("user:update:01")//用来判断权限字符串
public String save(){
//在代码中完成授权操作
//获取主体对象
Subject subject = SecurityUtils.getSubject();
if(subject.hasRole("admin")){
System.out.println("访问订单");
}else {
System.out.println("无权访问");
}
return "redirect:/index.jsp";
}
}
运行项目
根据权限不同显示内容不同