SpringBoot整合Shiro
1导入依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<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-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
2配置application.properties
#配置mysql
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql:///java2002?serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#mybatis
#扫描mapper.xml文件
mybatis.mapper-locations=classpath:mapper/*.xml
#sql语句显示到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#配置thymeleaf
spring.thymeleaf.prefix=classpath:/templates
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.mode=HTML
3编写ShiroRealm
package com.qf.realm;
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;
public class ShiroRealm extends AuthorizingRealm {
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
}
}
4编写ShiroConfig
package com.qf.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.qf.realm.ShiroRealm;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
@Configuration
public class ShiroConfig {
public ShiroRealm getShiroRealm(){
return new ShiroRealm();
}
@Bean
public SecurityManager getSecurityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(getShiroRealm());
return securityManager;
}
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/toLogin");
shiroFilterFactoryBean.setUnauthorizedUrl("/refuse");
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("/js/**","anon");
map.put("/css/**","anon");
map.put("/jquery/**","anon");
map.put("/layui/**","anon");
map.put("/login","anon");
map.put("/**","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
}
anon:admins
5创建controller
package com.qf.controller;
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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserController {
@RequestMapping("toLogin")
public String toLgoin(){
System.out.println("toLogin");
return "/login";
}
@RequestMapping("login")
public String login(){
System.out.println("login");
return "/login";
}
@RequestMapping("refuse")
public String refuse(){
System.out.println("refuse");
return "/refuse";
}
@RequestMapping("index")
public String index(){
System.out.println("index");
return "/index";
}
@RequestMapping("add")
public String add(){
System.out.println("add");
return "/add";
}
@RequestMapping("select")
public String select(){
System.out.println("select");
return "/select";
}
@RequestMapping("delete")
public String delete(){
System.out.println("delete");
return "/delete";
}
}
6编写对应的login.html页面(以及其他页面)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<center>
<form action="login">
用户名:<input type="text" name="username"><br> <br>
密码:<input type="password" name="password"><br> <br>
<input type="submit" value="登录">
</form>
</center>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1><font color="red">拒绝访问!!!</font> </h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>主页面</h1>
<a href="add">添加用户</a>
<a href="select">查询用户</a>
<a href="delete">删除用户</a>
<a href="update">修改用户</a>
<a href="/logout">退出</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加用户</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>查询用户</h1>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>删除用户</h1>
</body>
</html>
7实现用户认证,修改UserController中的login方法
@RequestMapping("login")
public String login(String username, String password){
System.out.println("login");
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
subject.login(token);
boolean authenticated = subject.isAuthenticated();
if(authenticated){
return "/index";
}
return "/login";
}
8修改ShiroRealm中的AuthenticationInfo方法
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String principal = (String)token.getPrincipal();
System.out.println(principal);
String credentials = new String((char[])token.getCredentials());
System.out.println(credentials);
if("jack".equals(principal) && "123".equals(credentials)){
return new SimpleAuthenticationInfo(principal,credentials,"ShiroRealm");
}
return null;
}
9实现用户授权,在ShiroConfig中的shiroFilter方法中添加被授权的信息
map.put("/delete","perms[user:delete]");
map.put("/select","perms[user:select]");
10修改ShiroRealm中的doGetAuthorizationInfo方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
HashSet<String> set = new HashSet<>();
set.add("user:select");
set.add("user:update");
simpleAuthorizationInfo.addStringPermissions(set);
return simpleAuthorizationInfo;
}
11Shiro整合thymleaf标签
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
12在ShiroConfig中添加该方法
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
13修改index.html页面中测试
<!DOCTYPE html>
<html lang="en" xmlns:shiro="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>主页面</h1>
<a href="add">添加用户</a>
<a href="select">查询用户</a>
<a href="delete" shiro:hasPermission="user:delete">删除用户</a>
<a href="update" shiro:hasPermission="user:update">修改用户</a>
<a href="/logout">退出</a>
</body>
</html>
14实现用户退出(两种方式),在相关index.html页面中添加超链接
<a href="/logout">退出</a>
15在ShiroConfig中的shiroFilter方法中添加退出配置(第一种)
map.put("/logout","logout");
16在UserController中添加logout方法(第二种)
@RequestMapping("logout")
public String logout(){
System.out.println("logout");
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "/login";
}
17记住我rememberMe,在login.html页面中添加记住我
<input type="checkbox" name="rememberMe">记住我<br> <br>
18在UserController中的login方法配置rememberMe参数
@RequestMapping("login")
public String login(String username, String password,boolean rememberMe){
System.out.println("login");
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password,rememberMe);
subject.login(token);
boolean authenticated = subject.isAuthenticated();
if(authenticated){
return "/index";
}
return "/login";
}
19在ShiroConfig类中添加相关方法以及代码
package com.qf.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.qf.realm.ShiroRealm;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
@Configuration
public class ShiroConfig {
@Bean
public CookieRememberMeManager getCookieRememberMeManager(){
SimpleCookie simpleCookie = new SimpleCookie("renemberMe");
simpleCookie.setMaxAge(3600*24*31);
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(simpleCookie);
return cookieRememberMeManager;
}
public ShiroRealm getShiroRealm(){
return new ShiroRealm();
}
@Bean
public SecurityManager getSecurityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(getShiroRealm());
securityManager.setRememberMeManager(getCookieRememberMeManager());
return securityManager;
}
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/toLogin");
shiroFilterFactoryBean.setUnauthorizedUrl("/refuse");
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("/js/**","anon");
map.put("/css/**","anon");
map.put("/jquery/**","anon");
map.put("/layui/**","anon");
map.put("/login","anon");
map.put("/logout","logout");
map.put("/delete","perms[user:delete]");
map.put("/select","perms[user:select]");
map.put("/index","user");
map.put("/**","authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
}