文章目录
- SpringBoot整合Shiro
- 1、导入依赖
- 2、配置application.properties
- 3、编写ShiroRealm
- 4、编写ShiroConfig
- 5、创建controller
- 6、编写对应的login.html页面(以及其他页面)
- 7、实现用户认证,修改UserController中的login方法
- 8、修改ShiroRealm中的AuthenticationInfo方法
- 9、实现用户授权,在ShiroConfig中的shiroFilter方法中添加被授权的信息
- 10、修改ShiroRealm中的doGetAuthorizationInfo方法
- 11、Shiro整合thymleaf标签
- 12、在ShiroConfig中添加该方法
- 13、修改index.html页面中测试
- 14、实现用户退出(两种方式),在相关index.html页面中添加超链接
- 15、在ShiroConfig中的shiroFilter方法中添加退出配置(第一种)
- 16、在UserController中添加logout方法(第二种)
- 17、记住我rememberMe,在login.html页面中添加记住我
- 18、在UserController中的login方法配置rememberMe参数
- 19、在ShiroConfig类中添加相关方法以及代码
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;
}
//Shiro过滤器配置
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager){
//创建Shiro工厂对象
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(securityManager);
//未认证访问页面
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//认证成功跳转页面(一般不设置,默认登录成功跳转当前页面)
//shiroFilterFactoryBean.setSuccessUrl("/index");
//未授权访问页面
shiroFilterFactoryBean.setUnauthorizedUrl("/refuse");
//通过map配置访问流程(顺序很重要)
LinkedHashMap<String, String> map = new LinkedHashMap<>();
//配置静态资源
map.put("/js/**","anon");
map.put("/css/**","anon");
map.put("/jquery/**","anon");
map.put("/layui/**","anon");
//配置login页面
map.put("/login","anon");
//配置logout退出
//map.put("/logout","logout");
//配置授权
//map.put("/delete","perms[user:delete]");
//map.put("/select","perms[user:select]");
//user设置记住我(二次登录不做认证操作)
//map.put("/index","user");
map.put("/**","authc");//该路径认证后才能访问
//map.put("/**","anon");//所有路径都可以匿名访问
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
}
过滤器简称 对应的java类 anon org.apache.shiro.web.filter.authc.AnonymousFilter authc org.apache.shiro.web.filter.authc.FormAuthenticationFilter authcBasic org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter perms org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter port org.apache.shiro.web.filter.authz.PortFilter rest org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter roles org.apache.shiro.web.filter.authz.RolesAuthorizationFilter ssl org.apache.shiro.web.filter.authz.SslFilter user org.apache.shiro.web.filter.authc.UserFilter logout org.apache.shiro.web.filter.authc.LogoutFilter
anon:admins/**=anon 没有参数,表示可以匿名使用。
authc:/admins/user/**=authc表示需要认证(登录)才能使用,FormAuthenticationFilter是表单认证,没有参数
roles:/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。
perms:/admins/user/**=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。
rest:/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,其中method为post,get,delete等。
port:/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString是你访问的url里的?后面的参数。
authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证
ssl:/admins/user/**=ssl没有参数,表示安全的url请求,协议为https
user:/admins/user/**=user没有参数表示必须存在用户, 身份认证通过或通过记住我认证通过的可以访问,当登入操作时不做检查
anon,authcBasic,auchc,user是认证过滤器
perms,roles,ssl,rest,port是授权过滤器
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";
}
// @RequestMapping("logout")
// public String logout(){
// System.out.println("logout");
// Subject subject = SecurityUtils.getSubject();
// subject.logout();
// return "/login";
// }
}
启动工程,进行测试
6、编写对应的login.html页面(以及其他页面)
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>
refuse.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1><font color="red">拒绝访问!!!</font> </h1>
</body>
</html>
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">删除用户</a>
<a href="update">修改用户</a>
<a href="/logout">退出</a>
</body>
</html>
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>添加用户</h1>
</body>
</html>
select.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>查询用户</h1>
</body>
</html>
delete.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;
}
11、Shiro整合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;
}
//配置ShiroDialect
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
//shiro过滤器配置
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//未认证访问页面
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//认证成功跳转页面(一般不设置,默认登录成功跳转当前页面)
//shiroFilterFactoryBean.setSuccessUrl("/index");
//未授权访问页面
shiroFilterFactoryBean.setUnauthorizedUrl("/refuse");
//通过map配置访问流程(顺序很重要)
LinkedHashMap<String, String> map = new LinkedHashMap<>();
//配置静态资源
map.put("/js/**","anon");
map.put("/css/**","anon");
map.put("/jquery/**","anon");
map.put("/layui/**","anon");
//配置login页面
map.put("/login","anon");
//配置logout退出
map.put("/logout","logout");
//配置授权
map.put("/delete","perms[user:delete]");
map.put("/select","perms[user:select]");
//user设置记住我(二次登录不做认证操作)
map.put("/index","user");
map.put("/**","authc");//该路径认证后才能访问
//map.put("/**","anon");//所有路径都可以匿名访问
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
return shiroFilterFactoryBean;
}
}