狂神shiro笔记

shiro的快速开始

maven配置:

<!-- 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>

log4j的配置:
log4j.properties
ini的配置
shiro.ini
测试一下?
Quickstart
基本类型
在这里插入图片描述
本章结束!!!!

shiro的subject分析

1. 首先使用factory(工厂)创建shiro.ini实例

2. 获取当前的用户对象(相对独立)

Subject currentUser = SecurityUtils.getSubject();

3. 通过当前用户拿到session

Session session = currentUser.getSession();

4. 登录认证

 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) {//用户锁定 lock
                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?
            }
        }

5. 角色和权限的认证

 //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")) {
            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!");
        }

SpringBoot集成shiro

面试小技巧?

	<!--
		Subject. 用户
		SecurityManager管理所有的用户
		Realm连接数据
	-->

1.springboot的包整合maven

<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring-boot-web-starter -->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-web-starter</artifactId>
    <version>1.7.1</version>
</dependency>

2.编写config的配置类

PS:@Bean必须加上

  1. shiroFilterFactoryBean
    //shiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaultWebSecurityManager") DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroBean.setSecurityManager(securityManager);
        return shiroBean;
    }
    
  2. DefaultWebSecurityManager2
//DefaultWebSecurityManager2
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){//方法把类名引入
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
  1. 创建Realm对象 需要自定义1

自定义一个UserRealm. 需要继承extends AuthorizingRealm

public class UserRealm extends AuthorizingRealm {

   //授权
   @Override
 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection >principalCollection) {
      System.out.println("执行授权=====》");
       return null;
  }

   //认证
   @Override
   protected AuthenticationInfo >doGetAuthenticationInfo(AuthenticationToken authenticationToken) >throws AuthenticationException {
       System.out.println("执行认证=====》");
      return null;
   }
} 
 //创建Realm对象 需要自定义1

    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

登录拦截器

//添加shiro内置过滤器
/**
* anon 无需认证皆可访问
* authc 必须认证才可以访问
* user 必须记住我才可以访问
* perms 拥有某个资源权限才可以访问
* role 拥有某个角色权限才可以访问
*
* **/


        Map<String,String> map = new LinkedHashMap<>();

        map.put("/admin/add","anon");
        map.put("/admin/update","authc");

		//设置登录请求
		 shiroBean.setLoginUrl("/login");

        //设置一个过滤器的链
        shiroBean.setFilterChainDefinitionMap(map);

在这里插入图片描述

在这里插入图片描述

用户认证

小结
请求写在第一个
用户认证写在realm
在userrealm写

静态编写用户密码认证

@RequestMapping("/loginin")
    public String loginYanzheng(
            String username,
            String password,
            Model model
            ){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        try {
            subject.login(token);//执行登录的方法,如果没有异常就OK了
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg","用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg","密码不存在");
            return "login";
        }

    }

//认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证=====》");

        String username = "jiangwenhan";
        String password = "123456";

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        if(!userToken.getUsername().equals(username)){
            return null;//抛出异常
        }

        //密码认证,shiro做

        return new SimpleAuthenticationInfo("",password,"");
    }

shiro和数据库的整合

PS:我是用的是JPA,使用什么都无所谓,道理都一样

认证处做了改变

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证=====》");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

//使用真实的数据库
        admin admin = this.adminDao.findByUsername(userToken.getUsername());

        if(admin==null){
            return null;//抛出异常
        }

        //密码认证,shiro做

        return new SimpleAuthenticationInfo(admin,admin.getPassword(),"");
    }

权限验证

主要是ShiroFilterFactoryBean里过滤器的链

List<prem> prem = this.premDao.findAll();
        for (int i = 0; i < prem.size(); i++) {
            map.put(prem.get(i).getSrc(),"perms[u"+prem.get(i).getId()+"]");
        }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权=====》");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject current = SecurityUtils.getSubject();
        admin admin = (admin) current.getPrincipal();

        List<rolePrem> rolePrems = this.rolePremDao.findByRoleId(admin.getRoleId());

        for (int i = 0; i < rolePrems.size(); i++) {
            info.addStringPermission("u"+rolePrems.get(i).getPremId().toString());
        }

        return info;
    }

shiro和thymeleaf的整合

千万不要忘了config里面加入

//整合shiroDialect thymeleaf-shiro
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
整理自尚硅谷视频教程springboot高级篇,并增加部分springboot2.x的内容 一、Spring Boot与缓存 一、JSR107 Java Caching定义了5个核心接口,分别是CachingProvider, CacheManager, Cache, Entry 和 Expiry。 • CachingProvider定义了创建、配置、获取、管理和控制多个CacheManager。一个应用可 以在运行 期访问多个CachingProvider。 • CacheManager定义了创建、配置、获取、管理和控制多个唯一命名 的Cache,这些Cache 存在于CacheManager的上下文中。一个CacheManager仅被一个 CachingProvider所拥有。 • Cache是一个类似Map的数据结构并临时存储以Key为索引的值。一个 Cache仅被一个 CacheManager所拥有。 • Entry是一个存储在Cache中的key-value对。 • Expiry 每一 个存储在Cache中的条目有一个定义的有效期。一旦超过这个时间,条目为过期 的状态。一旦过期,条 目将不可访问、更新和删除。缓存有效期可以通过ExpiryPolicy设置。 二、Spring缓存抽象 Spring从3.1开始定义了org.springframework.cache.Cache 和 org.springframework.cache.CacheManager接口来统一不同的缓存技术; 并支持使用JCache(JSR- 107)注解简化我们开发; • Cache接口为缓存的组件规范定义,包含缓存的各种操作集合; • Cache接 口下Spring提供了各种xxxCache的实现;如RedisCache,EhCacheCache , ConcurrentMapCache 等; • 每次调用需要缓存功能的方法时,Spring会检查检查指定参数的指定的目标方法是否 已经被调用 过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法 并缓存结果后返回给用户。下 次调用直接从缓存中获取。 • 使用Spring缓存抽象时我们需要关注以下两点; 1、确定方法需要被缓存 以及他们的缓存策略 2、从缓存中读取之前缓存存储的数据 Cache 缓存接口,定义缓存操作。实现有:RedisCache、EhCacheCache、 ConcurrentMapCache等 CacheManager 缓存管理器,管理各种缓存(Cache)组件 @Cacheable 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存 @CacheEvict 清空缓存 @CachePut 保证方法被调用,又希望结果被缓存。 @EnableCaching 开启基于注解的缓存 keyGenerator 缓存数据时key生成策略 serialize 缓存数据时value序列化策略 @CacheConfig 抽取缓存的公共配置 三、几个重要概念&缓存注解 1、常用注解 2、常用参数 名字 位置 描述 示例 methodName root object 当前被调用的方法名 #root.methodName method root object 当前被调用的方法 #root.method.name target root object 当前被调用的目标对象 #root.target targetClass root object 当前被调用的目标对象类 #root.targetClass args root object 当前被调用的方法的参数列表 #root.args[0] 3、常用参数SPEL说明 名字 位置 描述 示例 caches root object 当前方法调用使用的缓存列表(如 @Cacheable(value= {"cache1","cache2"}) ), 则有两 个cache #root.caches[0].name argument name evaluation context 方法参数的名字. 可以直接 #参数 名 ,也可以使用 #p0或#a0 的形 式,0代表参数的索引; #iban 、 #a0 、 #p0 result evaluation context 方法执行后的返回值(仅当方法执 行之后的判断有效,如‘unless’ , ’cache put’的表达式 ’cache evict’的表达式 beforeInvocation=false ) #result 四、代码中使用缓存 1、搭建基本环境 1、导入数据库文件 创建出department和employee表 2、创建javaBean封装数据 3、整合MyBatis操作数据库 1.配置数据源信息 2.使用注解版的MyBatis; 1)、@MapperScan指定需要扫描的mapper接口所在的包

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值