<dependency>
<groupId>org.apache.tomcat.embedgroupId>
<artifactId>tomcat-embed-jasperartifactId>
<version>7.0.59version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
因为有jsp,我们设置一下工作路径
application.properties(配置端口、路径、jsp等)
server.port=8081
server.servlet.context-path=/shrio
spring.application.name=shrio
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>jsp indextitle>
head>
<body>
<h1>1111h1>
body>
html>
依赖
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-spring-boot-web-starterartifactId>
<version>1.4.1version>
dependency>
开始配置shiro环境
新建shiro配置类ShiroConfig.java
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 {
@Bean( name="shiroFilterFactoryBean")
public ShiroFilterFactoryBean getFilter(DefaultWebSecurityManager defaultWebSecurityManager){
// 负责拦截所有请求
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 给filter设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
// 配置公共资源和受限资源
Map<String,String> map = new HashMap<String,String>();
map.put("/","authc"); // authc 表示请求这个资源需要认证和授权
map.put("/index.jsp","authc");
// 默认认证界面路径(也就是不管你访问哪个界面,都会先跳到这个界面认证)
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
@Bean
public DefaultWebSecurityManager getManager(Realm realm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
@Bean
public Realm getRealm(){
CustomerRealm customerRealm = new CustomerRealm();
return customerRealm;
}
}
新建CustomerRealm.java
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
* */
public class CustomerRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
}
}
所有请求都需要认证如下
如上图,有个authc表示请求这个资源需要认证和授权,更多过滤器如下
新建一个UserController.java
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("user")
public class UserController {
// 处理身份认证
@RequestMapping("login")
public String login(String username,String password){
//获取主体对象
Subject subject = SecurityUtils.getSubject();
try {
subject.login(new UsernamePasswordToken(username,password));
} catch (UnsupportedTokenException e) {
e.printStackTrace();
System.out.println("用户名错误");
} catch (IncorrectCredentialsException e) {
e.printStackTrace();
System.out.println("密码错误");
}
return "redirect:/index.jsp";
}
// 退出登录
@RequestMapping("logout")
public String logout(){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/login.jsp";
}
}
login.jsp
index.jsp
修改CustomerRealm.java
String principal = (String) authenticationToken.getPrincipal();
if ("zhang".equals(principal)) {
return new SimpleAuthenticationInfo(principal,"123",this.getName());
}
修改ShiroConfig.java
指定公共资源和需要认证的资源
pom中引入mysql、mybatis、druid依赖
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.19version>
dependency>
在mysql中新建库shiro,新建表t_user
create database shiro;
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(40) NOT NULL,
`password` varchar(40) NOT NULL,
`salt` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
application.properties配置数据库与mybatis
server.port=8081
server.servlet.context-path=/shrio
spring.application.name=shrio
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/shiro?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
mybatis.type-aliases-package=com.example.demo.entity
mybatis.mapper-locations=classpath:/mapper/*.xml
新建实体类User.java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
private String salt;
}
import com.example.demo.entity.User;
import org.springframework.stereotype.Service;
@Mapper
public interface UserDao {
void save(User user);
}
<mapper namespace="com.example.demo.dao.UserDao">
<insert id="save" parameterType="com.example.demo.entity.User" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(#{id},#{username},#{password},#{salt})
insert>
mapper>
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
public interface UserService {
// 用户注册
void register(User user);
}
添加一个注册页面regedit.jsp (从登录页面复制过来修改的)
在ShiroConfig,java里面放行注册页面、注册路径
新建工具类SaltUtils.java用来生成随机盐
import java.util.Random;
public class SaltUtils {
public static String getSalt(int n){
char[] chars = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP0123456789,./;'[]-=".toCharArray();
StringBuilder s = new StringBuilder();
for (int i=0;i<n;i++){
char a = chars[new Random().nextInt(chars.length)];
s.append(a);
}
return s.toString();
}
}
新建UserServiceImpl.java里面完成注册业务
import com.example.demo.SaltUtils;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
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;
@Service
@Transactional
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
public void register(User user) {
// 处理业务
// 密码md5+salt+hash散列
String salt = SaltUtils.getSalt(6);
Md5Hash newPassword = new Md5Hash(user.getPassword(),salt,1024);
user.setSalt(salt);
user.setPassword(newPassword.toHex());
userDao.save(user);
}
}
@Autowired
private UserService userService;
// 用户注册
@RequestMapping("register")
public String register(User user){
System.out.println(user.toString());
try {
// 注册成功,返回登录界面
userService.register(user);
return "redirect:/login.jsp";
} catch (Exception e) {
// 失败继续待在注册页面
e.printStackTrace();
System.out.println("注册失败");
return "redirect:/regedit.jsp";
}
}
运行项目试试能不能注册了
注册完看看数据库
目前项目目录结构
在UserDao接口中加入查询方法
在UserDaoMapper.xml里面实现查询数据库
在业务层接口添加上对应的方法
在业务层接口实现类添加上对应的方法
新建ApplicationContextUtils.java (用来在工厂中获取service对象)
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);
}
}
定义realm到目前全部代码 (这里添加了md5验证、加盐、散列)
CustomerRealm.java
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
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.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.ObjectUtils;
/*
* 自定义Realm
* */
public class CustomerRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String principal = (String) authenticationToken.getPrincipal();
// 在工厂中获取service对象
UserService us= (UserService) ApplicationContextUtils.getBean("userServiceImpl");
User user = us.findByUsername(principal);
if (!ObjectUtils.isEmpty(user)) {
return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
}
return null;
}
}
ShiroConfig.java到目前为止所有代码
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
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 {
@Bean( name="shiroFilterFactoryBean")
public ShiroFilterFactoryBean getFilter(DefaultWebSecurityManager defaultWebSecurityManager){
// 负责拦截所有请求
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 给filter设置安全管理器
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
// 配置公共资源和受限资源
Map<String,String> map = new HashMap<String,String>();
map.put("/user/login","anon"); // anon 这个资源不需要认证
map.put("/user/register","anon");
map.put("/regedit.jsp","anon");
map.put("/**","authc"); // authc 表示请求这个资源需要认证和授权
// 默认认证界面路径(也就是不管你访问哪个界面,都会先跳到这个界面认证)
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
@Bean
public DefaultWebSecurityManager getManager(Realm realm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
@Bean
public Realm getRealm(){
CustomerRealm customerRealm = new CustomerRealm();
// 修改凭证校验匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
// MD5
credentialsMatcher.setHashAlgorithmName("MD5");
// 设置散列次数
credentialsMatcher.setHashIterations(1024);
customerRealm.setCredentialsMatcher(credentialsMatcher);
return customerRealm;
}
}
如上运行后就能成功认证了
如果报错java.lang.NoSuchMethodError: org.apache.tomcat.JarScanner.scan…
可能是因为自己引入的tomcat版本和springboot自带的不一致导致出现此问题
所以要么删除自己引入的tomcat,要么去掉springboot内置的tomcat
这里我不需要外置tomcat,所以我删除了tomcat依赖
修改自定义Realm
CustomerRealm.java目前全部代码
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
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.ObjectUtils;
/*
* 自定义Realm
* */
public class CustomerRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
// 获取身份信息
String pp = (String) principalCollection.getPrimaryPrincipal();
// 根据主身份信息获取角色 和 权限信息
if("a".equals(pp)){
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRole("admin");
simpleAuthorizationInfo.addRole("user");
// simpleAuthorizationInfo.addStringPermission("user:*:* ");
simpleAuthorizationInfo.addStringPermission("user:add:* ");
simpleAuthorizationInfo.addStringPermission("user:del:* ");
}
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String principal = (String) authenticationToken.getPrincipal();
// 在工厂中获取service对象
UserService us= (UserService) ApplicationContextUtils.getBean("userService");
User user = us.findByUsername(principal);
if (!ObjectUtils.isEmpty(user)) {
return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
}
return null;
}
}
index.jsp目前全部代码
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>jsp indextitle>
head>
<body>
<h1>index界面h1>
<a href="${pageContext.request.contextPath}/user/logout">退出a>
<%--user或admin组都可以看到--%>
<shiro:hasAnyRoles name="user,admin">
<li><a href="">商品管理a>li>
<li><a href="">订单管理a>li>
shiro:hasAnyRoles>
<%--只有admin可以看到--%>
<shiro:hasRole name="admin">
<li><a href="">用户管理a>
<ul>
<shiro:hasPermission name="user:add:*">
<li><a href="">添加a>li>
shiro:hasPermission>
<shiro:hasPermission name="user:del:*">
<li><a href="">删除a>li>
shiro:hasPermission>
ul>
li>
<li><a href="">物流管理a>li>
shiro:hasRole>
body>
html>
新建OrderController.java
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
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;
/**
* @Author BeanInJ
* @Date 16:04 2021/1/14
**/
@Controller
@RequestMapping("order")
public class OrderController {
@RequestMapping("save")
// @RequiresRoles("admin") //判断角色
// @RequiresRoles(value = {"admin","user"}) //判断角色 同时具有admin、user
@RequiresPermissions("user:del:01") // 判断权限字符串
public String save(){
// 代码方式授权
Subject subject = SecurityUtils.getSubject();
if (subject.hasRole("admin")) {
System.out.println("保存订单");
}else {
System.out.println("无权访问");
}
return "redirect:/index.jsp";
}
}
在shiro数据库新建表t_role、t_perms、t_role_perms、t_user_role
DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
DROP TABLE IF EXISTS `t_pers`;
CREATE TABLE `t_pers` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
DROP TABLE IF EXISTS `t_role_perms`;
CREATE TABLE `t_role_perms` (
`id` int NOT NULL AUTO_INCREMENT,
`roleid` int DEFAULT NULL,
`permsid` int DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
DROP TABLE IF EXISTS `t_role`;
CREATE TABLE `t_role` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(60) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
添加三个角色
为用户添加对应的角色
新建表对应的实体类
Role.java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Role {
private int id;
private String name;
}
Perms.java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class Perms {
private int id;
private String name;
private String url;
}
在user实体类中定义角色集合
在UserDao里面增加根据用户名获取角色信息
<resultMap id="userMap" type="User">
<id column="uid" property="id" />
<result column="username" property="username" />
<!--角色信息-->
<collection property="roles" javaType="list" ofType="Role">
<id column="id" property="id" />
<result column="rname" property="name"/>
</collection>
</resultMap>
<select id="findRolesByUserName" parameterType="String" resultMap="">
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>
UserService添加findRolesByUserName查询方法
UserServiceImpl
修改自定义realm中的权限部分
UserService us= (UserService) ApplicationContextUtils.getBean("userService");
User user = us.findRolesByUserName(pp);
// 授权角色
if(!CollectionUtils.isEmpty(user.getRoles())){
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
user.getRoles().forEach(role -> {
simpleAuthorizationInfo.addRole(role.getName());
});
return simpleAuthorizationInfo;
}
到目前为止,做了认证、角色权限,项目目录结构我修改了一下,如下
ShiroConfig.java
import com.beaninj.shiro.util.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
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;
@Configuration
public class ShiroConfig {
@Bean(name = "shiroFilterFactoryBean")
public ShiroFilterFactoryBean getFilter(DefaultWebSecurityManager dwsManager) {
// 负责拦截所有请求
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 给filter设置安全管理器
shiroFilterFactoryBean.setSecurityManager(dwsManager);
// 配置公共资源和受限资源
Map<String, String> map = new HashMap<String, String>();
map.put("/**", "authc");
map.put("/user/login", "anon"); // anon 这个资源不需要认证
map.put("/user/register", "anon");
map.put("/register.jsp", "anon");
map.put("/login.jsp", "anon");
// authc 表示请求这个资源需要认证和授权
// 默认认证界面路径 (也就是不管你访问哪个界面,都会先跳到这个界面认证)
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
@Bean
public DefaultWebSecurityManager getManager(Realm realm) {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
@Bean
public Realm getRealm() {
MyRealm myRealm = new MyRealm();
// 修改凭证校验匹配器
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
// MD5
credentialsMatcher.setHashAlgorithmName("MD5");
// 设置散列次数
credentialsMatcher.setHashIterations(1024);
myRealm.setCredentialsMatcher(credentialsMatcher);
return myRealm;
}
}
UserServiceImpl.java
import com.beaninj.shiro.dao.UserDao;
import com.beaninj.shiro.entity.User;
import com.beaninj.shiro.util.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;
@Service("userService")
@Transactional // 开启事务
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void register(User user) {
// 密码md5+salt+hash散列
System.out.println("-----------------注册:存入md5+salt+hash散列的密码---------------");
String salt = SaltUtils.getSalt(6);
Md5Hash newPassword = new Md5Hash(user.getPassword(), salt, 1024);
user.setSalt(salt);
user.setPassword(newPassword.toHex());
userDao.save(user);
}
@Override
public User findByUsername(String username) {
return userDao.findByUsername(username);
}
@Override
public User findRolesByUserName(String username) {
return userDao.findRolesByUserName(username);
}
}
ApplicationContextUtils.java
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);
}
}
MyRealm.java
import com.beaninj.shiro.entity.User;
import com.beaninj.shiro.service.UserService;
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.apache.shiro.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
public class MyRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
// 获取身份信息
String pp = (String) principalCollection.getPrimaryPrincipal();
// 根据主身份信息获取角色 和 权限信息
UserService us = (UserService) ApplicationContextUtils.getBean("userService");
User user = us.findRolesByUserName(pp);
// 授权角色
if (!CollectionUtils.isEmpty(user.getRoles())) {
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
user.getRoles().forEach(role -> {
simpleAuthorizationInfo.addRole(role.getName());
});
return simpleAuthorizationInfo;
}
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
String principal = (String) authenticationToken.getPrincipal();
// 在工厂中获取service对象
UserService us= (UserService) ApplicationContextUtils.getBean("userService");
User user = us.findByUsername(principal);
if (!ObjectUtils.isEmpty(user)) {
return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
}
return null;
}
}
SaltUtils.java
import java.util.Random;
public class SaltUtils {
public static String getSalt(int n) {
char[] chars = "qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP0123456789,./;'[]-=".toCharArray();
StringBuilder s = new StringBuilder();
for (int i = 0; i < n; i++) {
char a = chars[new Random().nextInt(chars.length)];
s.append(a);
}
return s.toString();
}
}
UserDaoMapper.xml
<mapper namespace="com.beaninj.shiro.dao.UserDao">
<insert id="save" parameterType="com.beaninj.shiro.entity.User" useGeneratedKeys="true" keyProperty="id">
insert into t_user values(#{id},#{username},#{password},#{salt})
insert>
<select id="findByUsername" parameterType="String" resultType="com.beaninj.shiro.entity.User">
select id,username,password,salt from t_user
where username = #{username}
select>
<resultMap id="userMap" type="User">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<collection property="roles" javaType="list" ofType="Role">
<id column="id" property="id"/>
<result column="rname" property="name"/>
collection>
resultMap>
<select id="findRolesByUserName" parameterType="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>
mapper>
application.properties
server.port=8081
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.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/shiro?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
mybatis.type-aliases-package=com.beaninj.shiro.entity
mybatis.mapper-locations=classpath:/mapper/*.xml
logging.level.com.example.demo.dao=debug
index.jsp
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>jsp indextitle>
head>
<body>
<h1>index界面h1>
<a href="${pageContext.request.contextPath}/user/logout">退出a>
user或admin组都可以看到
<shiro:hasAnyRoles name="user,admin">
<li><a href="">商品管理a>li>
<li><a href="">订单管理a>li>
shiro:hasAnyRoles>
<%--只有admin可以看到--%>
<shiro:hasRole name="admin">
<li><a href="">用户管理a>
<ul>
<shiro:hasPermission name="user:add:*">
<li><a href="">添加a>li>
shiro:hasPermission>
<shiro:hasPermission name="user:del:*">
<li><a href="">删除a>li>
shiro:hasPermission>
ul>
li>
<li><a href="">物流管理a>li>
shiro:hasRole>
body>
html>
logoin.jsp
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>jsp logintitle>
head>
<body>
<h1>请先登录h1>
<a href="register.jsp">注册a>
<form action="${pageContext.request.contextPath}/user/login">
用户名:<input type="text" name="username"> <br>
密码:<input type="text" name="password"> <br>
<input type="submit" value="登录">
form>
body>
html>
register.jsp
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>jsp regedittitle>
head>
<body>
<h1>注册页面h1>
<form action="${pageContext.request.contextPath}/user/register">
用户名:<input type="text" name="username"> <br>
密码:<input type="text" name="password"> <br>
<input type="submit" value="注册">
form>
body>
html>
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.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.4.1version>
<relativePath/>
parent>
<groupId>com.beaninjgroupId>
<artifactId>springboot_shiroartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>springboot_shironame>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<version>2.4.0version>
dependency>
<dependency>
<groupId>org.apache.tomcat.embedgroupId>
<artifactId>tomcat-embed-jasperartifactId>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.19version>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.2version>
dependency>
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-spring-boot-web-starterartifactId>
<version>1.4.1version>
dependency>
dependencies>
project>