目录

Shiro核心三大对象

Quickstart核心:

第一个Shiro程序

hello-shrio

1.pom.xml

2.编写Shiro配置

log4j.properties

shiro.ini

3、Quickstart

核心:

SpringBoot中集成 Shiro

环境搭建

1.pom.xml

2.index.html

3.MyController

4.ShiroConfig  需要realm 对象需自定义

5.UserRealm

6.ShiroConfig  倒着写

7.添加页面

8.测试

用户拦截

拦截:        ShiroConfig--ShiroFilterFactoryBean

跳转到登录页

Shrio使用用户认证

Shrio整合 Mybatis

1.pom.xml

2.application.yml

3.pojo

user

4.dao

UserDao

UserMapper

5.service

UserService

UserServiceImpl

测试: ApplicationTests

6.UserRealm  从数据库中获取数据

授权

1.授权 ShiroConfig--ShiroFilterFactoryBean

2.noAuth.html  未授权页面

3.设置未授权的请求

4.授权

5.从数据库中获取授权

权限选择

pom.xml

index.html

登录成功获取session

目录

ShiroConfig

UserRealm

MyController



Shiro核心三大对象

  1. Subject                  用户
  2. SecurityManager  管理所有用户
  3. 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.3Shiro架构(外部)

从外部来看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.4Shiro架构(内部)
  • 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, stdoutlog4j.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("核心代码");//获取当前用户对象  SubjectSubject currentUser = SecurityUtils.getSubject();//通过当前用户 获取获取sessionSession 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:eagle5log.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 {//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("授权=======>principalCollection");return null;}//认证@Overrideprotected 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@Beanpublic 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对象 需要自定义@Beanpublic 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:拥有某个角色权限才能访问*///链式 一般使用 LinkedHashMapMap<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);//获取当前用户subjectSubject 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
    //认证@Overrideprotected 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: 8080spring:datasource:driver-class-name: com.mysql.cj.jdbc.Drivername: defaultDataSourceusername: rootpassword: 123456url: jdbc:mysql://localhost:3306/mapper?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTCtype: com.alibaba.druid.pool.DruidDataSource#Spring Boot 默认是不注入这些属性值的,需要自己绑定#druid 数据源专有配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: 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 mapperPUBLIC "-//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 {@Autowiredprivate UserDao userDao;@Overridepublic User queryUserByName(String name) {return userDao.queryUserByName(name);}
}

测试: ApplicationTests

@SpringBootTest
class ApplicationTests {@AutowiredUserServiceImpl userService;@Testvoid contextLoads() {System.out.println(userService.queryUserByName("大白"));}}

6.UserRealm  从数据库中获取数据

//自定义  UserRealm   extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {@Autowiredprivate UserService userService;//授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("授权=======>principalCollection");return null;}//认证@Overrideprotected 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/toAddfilterMap.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.授权

    //授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {System.out.println("授权=======>principalCollection");SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();info.addStringPermission("user:add");return info;}

5.从数据库中获取授权

数据库user表增加一个字段perms

    //授权@Overrideprotected 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@Beanpublic 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@Beanpublic ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("webSecurityManager") DefaultWebSecurityManager webSecurityManager) {ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();//设置安全管理器bean.setSecurityManager(webSecurityManager);//添加shiro的内置拦截器/*** anon:无需认证就能访问* authc:必须认证才能访问* user:必须拥有'记住我'功能才能访问* perms:拥有某个资源的权限才能访问* role:拥有某个角色权限才能访问*///链式 一般使用 LinkedHashMapMap<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/toAddfilterMap.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对象 需要自定义@Beanpublic UserRealm userRealm() { //userRealm1 相当于别名return new UserRealm();}//ShiroDialect  shiro整合thymeleaf@Beanpublic 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 {@Autowiredprivate UserService userService;//授权@Overrideprotected 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;}//认证@Overrideprotected 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);//获取当前用户subjectSubject 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";}
}

012SpringBoot-Shiro(安全框架)相关推荐

  1. Shiro安全框架【快速入门】就这一篇!

    Shiro 简介 照例又去官网扒了扒介绍: Apache Shiro™ is a powerful and easy-to-use Java security framework that perfo ...

  2. 在Spring MVC中使用Apache Shiro安全框架

    我们在这里将对一个集成了Spring MVC+Hibernate+Apache Shiro的项目进行了一个简单说明.这个项目将展示如何在Spring MVC 中使用Apache Shiro来构建我们的 ...

  3. Shiro安全框架的使用

    Shiro安全框架 1.介绍 Shiro有三个核心的概念:Subject.SecurityManager和Realms. Subject(主体): subject本质上是当前正在执行的用户的特定于安全 ...

  4. 大数据WEB阶段 shiro安全控制框架

    shiro安全框架 零.目录 问题引申 shiro介绍 shiro工作流程 使用shiro 进行登录操作 使用shiro进行权限管理 一. 问题引申 需要实现的功能: 用户没有登录的情况下 , 处理登 ...

  5. java权限框架_Java高级工程师必备技术栈-由浅入深掌握Shiro权限框架

    权限系统在任何一个系统中都存在,随着分布式系统的大行其道,权限系统也趋向服务化,对于一个高级工程师来说,权限系统的设计是必不可少需要掌握的技术栈 Apache Shiro™是一个功能强大且易于使用的J ...

  6. shiro subject.getprincipal()为null_(变强、变秃)Java从零开始之Shiro安全框架

    Shiro安全框架 一.Shiro简介 二.Shiro架构图 三.Shiro涉及常见名词 四.Shiro配置文件详解 shiro.ini 文件放在 classpath 下 ,shiro 会自动查找.其 ...

  7. thymeleaf模板引擎shiro集成框架

    shiro权限框架.前端验证jsp设计.间tag它只能用于jsp系列模板引擎. 使用最近项目thymeleaf作为前端模板引擎,采用HTML档,未出台shiro的tag lib,假设你想利用这段时间s ...

  8. (转) shiro权限框架详解06-shiro与web项目整合(上)

    http://blog.csdn.net/facekbook/article/details/54947730 shiro和web项目整合,实现类似真实项目的应用 本文中使用的项目架构是springM ...

  9. Shiro 安全框架

    简介: Apache Shiro提供了认证.授权.加密和会话管理功能,将复杂的问题隐藏起来,提供清晰直观的API使开发者可以很轻松地开发自己的程序安全代码.并且在实现此目标时无须依赖第三方的框架.容器 ...

  10. 视频教程-Apache Shiro权限框架实战+项目案例视频课程-Java

    Apache Shiro权限框架实战+项目案例视频课程 拥有10余年项目实战经验. 2006-2011在nttdata从事对日软件开发类工作. 2011-2015在HP从事技术服务工作. 擅长于j2e ...

最新文章

  1. 快讯 | 首期“医工结合系列研讨会”汇聚清华力量,共促医工融合发展
  2. 关于系统弹出错误:429 , ActiveX 部件不能创建对象 的解决方法
  3. DELPHI 7 动态链接库DLL断点调试
  4. 《剑指Offer》38:字符串的排列
  5. [LeetCode]819. 最常见的单词
  6. CSS两栏布局之左栏布局
  7. 【数据分析】目标优化矩阵表确定权重
  8. 做港台项目开发遇到的一些非技术问题总汇。。。
  9. 量化策略回测DualThrust
  10. HTML5+CSS+DIV 新海诚电影简介
  11. HDU 1275(两车追及或相遇问题)
  12. Kotlin可能带来的一个深坑,系列篇
  13. html给页面整体添加左右边距_DIV CSS padding内补白(内边距)left right top bottom案例教程...
  14. 自制紧张刺激的滑雪游戏,来一把?
  15. Nim游戏入门+SG函数
  16. hdlc和ppp的pap认证和cahp认证,gre和mgre的使用和详解,nat地址的转换
  17. 文字翻译软件哪个好用?亲测好用的软件分享
  18. mysql中TINYINT的取值范围
  19. 用DC-DC 升压降压以及产生负电压的原理及应用
  20. 计算机网络工程这专业都学什么,我是学计算机网络工程专业的,我想问一下我以后可以从事哪些方面的工作呀...

热门文章

  1. Android学习之路(4)——小案例
  2. 测试开发(社招):58同城
  3. braintree支付开发整合paypal
  4. OpenCV之图像直方图
  5. 描述cookie隔离的好处_综合一
  6. 为什么深度学习模型不能适配不同的显微镜扫描仪产生的图像
  7. 使用xlrd模块读取Excel工作簿信息
  8. 前端_浅谈页面编写逻辑
  9. 软银开放Pepper开发,给机器人写安卓App是怎样一种体验?
  10. 这8方面搞定了,才能找到一份好工作!