目录
拦截: ShiroConfig--ShiroFilterFactoryBean
1.授权 ShiroConfig--ShiroFilterFactoryBean
Shiro核心三大对象
- Subject 用户
- SecurityManager 管理所有用户
- Realm 连接数据
Quickstart核心:
//获取当前用户对象 Subject Subject currentUser = SecurityUtils.getSubject();
//通过当前用户 获取获取session Session session = currentUser.getSession();
//判断用户是否认证 if (!currentUser.isAuthenticated()) { // 获取当前用户的认证 存取信息 currentUser.getPrincipal()//判断用户是否有某个角色 if (currentUser.hasRole("schwartz")) {
//检测你是否有什么样的权限 if (currentUser.isPermitted("lightsaber:wield")) {
//注销 currentUser.logout();
Shiro
简介
1.1
、什么是
Shiro
?
- Apache Shiro 是一个Java 的安全(权限)框架。
- Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。
- Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等。
- 下载地址:Apache Shiro | Simple. Java. Security.
- GitHub:GitHub - apache/shiro: Apache Shiro
1.2
、有哪些功能?
- Authentication:身份认证、登录,验证用户是不是拥有相应的身份;
- Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限,即判断用户能否 进行什么操作,如:验证某个用户是否拥有某个角色,或者细粒度的验证某个用户对某个资源是否具有某个权限!
- Session Manager:会话管理,即用户登录后就是第一次会话,在没有退出之前,它的所有信息都 在会话中;会话可以是普通的JavaSE环境,也可以是Web环境;
- Cryptography:加密,保护数据的安全性,如密码加密存储到数据库中,而不是明文存储;
- Web Support:Web支持,可以非常容易的集成到Web环境;
- Caching:缓存,比如用户登录后,其用户信息,拥有的角色、权限不必每次去查,这样可以提高效率
- Concurrency:Shiro支持多线程应用的并发验证,即,如在一个线程中开启另一个线程,能把权限自动的传播过去
- Testing:提供测试支持;
- Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;
- Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了
1.3、Shiro架构(外部)
从外部来看
Shiro
,即从应用程序角度来观察如何使用
shiro
完成工作
subject:
应用代码直接交互的对象是
Subject
,也就是说
Shiro
的对外
API
核心就是
Subject
,
Subject
代表了当前的用户,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是
Subject
,如网络爬虫,机器人等,与
Subject
的所有交互都会委托给
SecurityManager
;
Subject
其
实是一个门面,
SecurityManageer
才是实际的执行者
SecurityManager:
安全管理器,即所有与安全有关的操作都会与
SercurityManager
交互,并且它
管理着所有的
Subject
,可以看出它是
Shiro
的核心,它负责与
Shiro
的其他组件进行交互,它相当于
SpringMVC
的
DispatcherServlet
的角色
Realm
:
Shiro
从
Realm
获取安全数据(如用户,角色,权限),就是说
SecurityManager
要验证
用户身份,那么它需要从
Realm
获取相应的用户进行比较,来确定用户的身份是否合法;也需要从 Realm得到用户相应的角色、权限,进行验证用户的操作是否能够进行,可以把
Realm
看成
DataSource
;
1.4
、
Shiro
架构(内部)
- Subject:任何可以与应用交互的 ‘用户’;
- Security Manager:相当于SpringMVC中的DispatcherServlet;是Shiro的心脏,所有具体的交互都通过Security Manager进行控制,它管理者所有的Subject,且负责进行认证,授权,会话,及缓存的管理。
- Authenticator:负责Subject认证,是一个扩展点,可以自定义实现;可以使用认证策略 (Authentication Strategy),即什么情况下算用户认证通过了;
- Authorizer:授权器,即访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的那些功能;
- Realm:可以有一个或者多个的realm,可以认为是安全实体数据源,即用于获取安全实体的,可以用JDBC实现,也可以是内存实现等等,由用户提供;所以一般在应用中都需要实现自己的realm
- SessionManager:管理Session生命周期的组件,而Shiro并不仅仅可以用在Web环境,也可以用在普通的JavaSE环境中
- CacheManager:缓存控制器,来管理如用户,角色,权限等缓存的;因为这些数据基本上很少改变,放到缓存中后可以提高访问的性能;
- Cryptography:密码模块,Shiro 提高了一些常见的加密组件用于密码加密,解密等
第一个Shiro程序
Shiro教程:10 Minute Tutorial on Apache Shiro | Apache ShiroApache Shiro Tutorial | Apache Shiro10 Minute Tutorial on Apache Shiro | Apache Shiro
hello-shrio
1.pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/jcl-over-slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.1</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.1</version>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
<scope>runtime</scope>
</dependency>
</dependencies>
2.编写Shiro配置
log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
shiro.ini
[users]
root = secret, admin
guest = guest, guest
presidentskroob = 12345, president
darkhelmet = ludicrousspeed, darklord, schwartz
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
# roleName = perm1, perm2, ..., permN
# -----------------------------------------------------------------------------
[roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5
3、Quickstart
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
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 {
//使用日志们门面 使用log 输出
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
// The easiest way to create a Shiro SecurityManager with configured 一个简单的案例方式 告诉你如何创建一个Shiro SecurityManager 的安全管理 通过配置
// realms, users, roles and permissions is to use the simple INI config. 领域,用户,角色和权限是使用简单的INI配置。 就是 加载 shiro.ini 配置文件
// We'll do that by using a factory that can ingest a .ini file and 我们通过工厂默认读取配置文件
// return a SecurityManager instance: 返回一个SecurityManager实例
// Use the shiro.ini file at the root of the classpath 使用 shiro.ini 根目录下 就是 classpath 下
// (file: and url: prefixes load from files and urls respectively):
// Factory 工厂模式
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
// for this simple example quickstart, make the SecurityManager //对于这个简单的快速入门的例子,让SecurityManager
// accessible as a JVM singleton. Most applications wouldn't do this //可访问的JVM单例。 大多数应用程序不会这样做
// and instead rely on their container configuration or web.xml for //而是依赖于它们的容器配置或web.xml
// webapps. That is outside the scope of this simple quickstart, so // webapps。 这超出了简单快速入门的范围,所以
// we'll just do the bare minimum so you can continue to get a feel //我们只做最小值,所以你可以继续感觉
// for things. //对的事情。
SecurityUtils.setSecurityManager(securityManager);
System.out.println("--------------上面死代码-----------------------");
System.out.println("核心代码");
//获取当前用户对象 Subject
Subject currentUser = SecurityUtils.getSubject();
//通过当前用户 获取获取session
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Subject=> session [" + value + "]");
}
//判断用户是否认证
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) { //用户被锁定 比如 5次密码 不对
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")) { //检测你是否有什么样的权限 shiro.ini 中 drive:eagle5
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!");
}
//注销
currentUser.logout();
//结束
System.exit(0);
}
}
核心:
//获取当前用户对象 Subject Subject currentUser = SecurityUtils.getSubject();
//通过当前用户 获取获取session Session session = currentUser.getSession();
//判断用户是否认证 if (!currentUser.isAuthenticated()) { // 获取当前用户的认证 存取信息 currentUser.getPrincipal()//判断用户是否有某个角色 if (currentUser.hasRole("schwartz")) {
//检测你是否有什么样的权限 if (currentUser.isPermitted("lightsaber:wield")) {
//注销 currentUser.logout();
结果:
SpringBoot中集成 Shiro
环境搭建
1.pom.xml
<!-- spring整合shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.7.1</version>
</dependency>
2.index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="https://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
</body>
</html>
3.MyController
@Controller
public class MyController {
@RequestMapping({"/", "/index"})
public String toIndex(Model model) {
model.addAttribute("msg", "Hello Shiro");
return "index";
}
}
4.ShiroConfig 需要realm 对象需自定义
package com.gh.config;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Subject:用户
* SecurityManager:管理所有用户
* Realm:连接数据
*/
@Configuration
public class ShiroConfig {
//3.ShiroFilterFactoryBean
//2.DefaultWebSecurityManager
//1.创建realm对象 需要自定义
}
5.UserRealm
extends AuthorizingRealm
//自定义 UserRealm extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权=======>principalCollection");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证======>authenticationToken");
return null;
}
}
6.ShiroConfig 倒着写
package com.gh.config;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Subject:用户
* SecurityManager:管理所有用户
* Realm:连接数据
*/
@Configuration
public class ShiroConfig {
//3.ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("webSecurityManager") DefaultWebSecurityManager webSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(webSecurityManager);
return bean;
}
//2.DefaultWebSecurityManager
@Bean(name = "webSecurityManager") //不写 默认方法名
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
webSecurityManager.setRealm(userRealm);
return webSecurityManager;
}
//1.创建realm对象 需要自定义
@Bean
public UserRealm userRealm() { //userRealm1 相当于别名
return new UserRealm();
}
}
7.添加页面
add.html 、update.html 简单页面
controller
@RequestMapping("/user/toAdd")
public String toAdd() {
return "user/add";
}
@RequestMapping("/user/toUpdate")
public String toUpdate() {
return "user/update";
}
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="https://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<a th:href="@{/user/toAdd}">新增</a>
<a th:href="@{/user/toAdd}">新增</a>
</body>
</html>
8.测试
用户拦截
拦截:
ShiroConfig--ShiroFilterFactoryBean
//添加shiro的内置拦截器
/**
* anon:无需认证就能访问
* authc:必须认证才能访问
* user:必须拥有'记住我'功能才能访问
* perms:拥有某个资源的权限才能访问
* role:拥有某个角色权限才能访问
*/
//链式 一般使用 LinkedHashMap
Map<String, String> filterMap = new LinkedHashMap<>();
//授权
filterMap.put("/user/toAdd","authc");
filterMap.put("/user/toUpdate","authc");
//支持通配符
// filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
Map<String, String> filterMap = new LinkedHashMap<>(); filterMap.put("/user/*","authc"); bean.setFilterChainDefinitionMap(filterMap);
拦截成功
跳转到登录页
login.html、controller
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<form method="get" th:action="@{/login}">
<p>
用户名:<input type="text" name="username"/>
</p>
<p>
密码:<input type="password" name="password"/>
</p>
<input type="submit" value="登录"/>
</form>
</body>
</html>
@RequestMapping("/toLogin")
public String toLogin() {
return "login";
}
ShiroConfig--ShiroFilterFactoryBean
//设置登录的请求 bean.setLoginUrl("/toLogin");
Shrio使用用户认证
一、MyController
@RequestMapping("/login")
public String login(String username, String password, Model model) {
System.out.println("===========>"+username);
System.out.println("===========>"+password);
//获取当前用户subject
Subject user = SecurityUtils.getSubject();
//封装用户的登录数据 token 令牌
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
user.login(token);//执行的那登录方法,如果没有异常就说明OK了
return "index";
} catch (UnknownAccountException e) {
//用户名错误
model.addAttribute("msg","用户名错误!!!");
return "login";
}catch (IncorrectCredentialsException e){
//密码错误
model.addAttribute("msg","密码错误!!!");
return "login";
}
}
执行:进入了认证方法
二、认证:
UserRealm
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证======>authenticationToken");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;//固定套路 转换成我们认识的Token 就可以拿到登录信息
//假设用户名和密码 数据库中取
String username = "root";
String password = "123456";
if (!userToken.getUsername().equals(username)){
return null;//抛出异常 UnknownAccountException
}
/*
三个参数
获取当前用户的认证
用户密码
认证名
*/
return new SimpleAuthenticationInfo("",password, "");
}
Shrio整合 Mybatis
1.pom.xml
<!-- mysql数据库连接依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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.1.10</version>
</dependency>
<!-- mybatis-springboot -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
2.application.yml
# 应用服务 WEB 访问端口
server:
port: 8080
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
name: defaultDataSource
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mapper?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3.pojo
user
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private Integer id;
private String name;
private String pwd;
}
4.dao
UserDao
@Repository
@Mapper
public interface UserDao {
/**
* 登录
* @param name
* @return
*/
User queryUserByName(String name);
}
UserMapper
<?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.gh.dao.UserDao">
<select id="queryUserByName" resultType="com.gh.pojo.User" parameterType="String">
SELECT * FROM `user` WHERE `name` = #{name}
</select>
</mapper>
5.service
UserService
public interface UserService {
/**
* 登录
* @param name
* @return
*/
User queryUserByName(String name);
}
UserServiceImpl
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User queryUserByName(String name) {
return userDao.queryUserByName(name);
}
}
测试: ApplicationTests
@SpringBootTest
class ApplicationTests {
@Autowired
UserServiceImpl userService;
@Test
void contextLoads() {
System.out.println(userService.queryUserByName("大白"));
}
}
6.UserRealm 从数据库中获取数据
//自定义 UserRealm extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权=======>principalCollection");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证======>authenticationToken");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;//固定套路 转换成我们认识的Token 就可以拿到登录信息
//连接真实数据库
User user = userService.queryUserByName(userToken.getUsername());
//判断用户是否存在
if (user == null) { //没有这个人
return null; //抛出UnknownAccountException
}
//登录成功 往session中存储user信息
Subject currentUser = SecurityUtils.getSubject();
currentUser.getSession().setAttribute("user",currentUser);
/*
三个参数
获取当前用户的认证
用户密码
认证名
*/
//密码认证 shrio~ 做 加密了
return new SimpleAuthenticationInfo("",user.getPwd(), "");
}
}
授权
1.授权 ShiroConfig--ShiroFilterFactoryBean
//资源权限
filterMap.put("/user/toAdd","perms[user:add]"); // 只有带user:add 的用户才可以访问 /user/toAdd
filterMap.put("/user/toUpdate", "perms[user:update]");
2.noAuth.html 未授权页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 style="color: red">
对不起,没有权限访问该资源!!!
</h1>
</body>
</html>
3.设置未授权的请求
ShiroConfig--ShiroFilterFactoryBean
bean.setUnauthorizedUrl("/noAuth");
4.授权
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权=======>principalCollection");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");
return info;
}
5.从数据库中获取授权
数据库user表增加一个字段perms
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权=======>principalCollection");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");
//拿到当前登录的对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal(); //拿到User对象
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
注意:需要于认证绑定
权限选择
pom.xml
<!-- shiro-thymeleaf -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
需要配置: ShiroConfig 才可使用
//ShiroDialect shiro整合thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="https://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<!--从session 判断值-->
<div th:if="${session.loginUser}==null">
<a th:href="@{/toLogin}">登录</a>
</div>
<p th:text="${msg}"></p>
<div shiro:hasPermission="user:add"> <!--hasPermission是否拥有这个权限-->
<a th:href="@{/user/toAdd}">新增</a>
</div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/toUpdate}">修改</a>
</div>
</body>
</html>
登录成功获取session
UserRealm //认证 中
//登录成功 往session中存储user信息
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",currentUser);
目录
ShiroConfig
package com.gh.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Subject:用户
* SecurityManager:管理所有用户
* Realm:连接数据
*/
@Configuration
public class ShiroConfig {
//3.ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("webSecurityManager") DefaultWebSecurityManager webSecurityManager) {
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(webSecurityManager);
//添加shiro的内置拦截器
/**
* anon:无需认证就能访问
* authc:必须认证才能访问
* user:必须拥有'记住我'功能才能访问
* perms:拥有某个资源的权限才能访问
* role:拥有某个角色权限才能访问
*/
//链式 一般使用 LinkedHashMap
Map<String, String> filterMap = new LinkedHashMap<>();
//授权
filterMap.put("/user/toAdd","authc");
filterMap.put("/user/toUpdate","authc");
//支持通配符
// filterMap.put("/user/*","authc");
//资源权限 正常情况下,没有授权的会跳转到未授权页面
filterMap.put("/user/toAdd","perms[user:add]"); // 只有带user:add 的用户才可以访问 /user/toAdd
filterMap.put("/user/toUpdate","perms[user:update]");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
//设置未授权的请求
bean.setUnauthorizedUrl("/noAuth");
return bean;
}
//2.DefaultWebSecurityManager
@Bean(name = "webSecurityManager") //不写 默认方法名
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
DefaultWebSecurityManager webSecurityManager = new DefaultWebSecurityManager();
webSecurityManager.setRealm(userRealm);
return webSecurityManager;
}
//1.创建realm对象 需要自定义
@Bean
public UserRealm userRealm() { //userRealm1 相当于别名
return new UserRealm();
}
//ShiroDialect shiro整合thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
UserRealm
package com.gh.config;
import com.gh.pojo.User;
import com.gh.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.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
//自定义 UserRealm extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权=======>principalCollection");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");
//拿到当前登录的对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal(); //拿到User对象
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证======>authenticationToken");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;//固定套路 转换成我们认识的Token 就可以拿到登录信息
//连接真实数据库
User user = userService.queryUserByName(userToken.getUsername());
//判断用户是否存在
if (user == null) { //没有这个人
return null; //抛出UnknownAccountException
}
//登录成功 往session中存储user信息
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
/*
三个参数
获取当前用户的认证
用户密码
认证名
*/
//密码认证 shrio~ 做 加密了
return new SimpleAuthenticationInfo(user,user.getPwd(), "");
}
}
MyController
package com.gh.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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@RequestMapping({"/", "/index"})
public String toIndex(Model model) {
model.addAttribute("msg", "Hello Shiro");
return "index";
}
@RequestMapping("/user/toAdd")
public String toAdd() {
return "user/add";
}
@RequestMapping("/user/toUpdate")
public String toUpdate() {
return "user/update";
}
@RequestMapping("/toLogin")
public String toLogin() {
return "login";
}
@RequestMapping("/login")
public String login(String username, String password, Model model) {
System.out.println("===========>"+username);
System.out.println("===========>"+password);
//获取当前用户subject
Subject user = SecurityUtils.getSubject();
//封装用户的登录数据 token 令牌
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
user.login(token);//执行的那登录方法,如果没有异常就说明OK了
return "index";
} catch (UnknownAccountException e) {
//用户名错误
model.addAttribute("msg","用户名错误!!!");
return "login";
}catch (IncorrectCredentialsException e){
//密码错误
model.addAttribute("msg","密码错误!!!");
return "login";
}
}
@RequestMapping("/noAuth")
public String author(){
return "noAuth";
}
}