SpringBoot + Shiro 详解+使用案列

SpringBoot整合Shiro之Thymeleaf使用Shiro标签 目录`thymeleaf` 模板引擎使用 `shiro` 标签 thymeleaf 模板引擎使用 shiro 标签 我们紧接着 上一篇 文章,我们使用账号 jack 和账号 Tom 来分别登录,在上一篇文章测试中可以看到,这两个账号无论哪一个登录,首页页面都会显示 add 页面和 update 页面两个超链接,而对于这两个账号来说,一个拥有访问 add 页面的权限,一个拥有访问 update 页面的权限。那么问题来了,如何才能根据对应用户的身份角色来显示对应的页面呢?这就要使用 shiro 标签了 .. 阅读详情

初始shiro

文章目录



一、shiro是什么?

1.shiro简介

官网地址:shiro官网
Apache Shiro是一个强大且易用的Java安全框架,用来进行身份验证、授权、密码和会话管理。使用Shiro的易于理解API,你可以快速、轻松地获取任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序

2.结构分析

shiro架构图:官网架构图

(1)从外部整体看shiro框架

即从应用程序角度来看,shiro是如何来进行工作的。
在这里插入图片描述

api说明
Subject主体,应用代码直接交互的对象是 Subject,也就是说 Shiro 的对外 API 核心就是 Subject , 代表了当前“用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等;即一个抽象概念;所有Subject都绑定到SecurityManager,与Subject的所有交互都会委托给SecurityManager;可以把Subject认为是一个门面;SecurityManager才是实际的执行者;
ShiroSecurityManager安全管理器,即所有与安全有关的操作都会与SecurityManager交互且它管理着所有Subject;可以看出它是Shiro的核心,它负责与后面介绍的其它组件进行交互,可以把它看成DispathcherServlet前端控制器
Realm域,Shiro从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源

也就是说最简单的一个Shiro应用:
1、应用代码通过Subject来进行认证和授权,而Subject又委托给SecurityManager;
2、我们需要给Shiro的SecurityManager注入Realm,从而让SecurityManager能得到合法的用户及其权限进行判断。
从以上也可以看出,Shiro不提供维护用户/权限,而是通过Realm让开发人员自己注入。

(2)从外部整体看shiro框架

在这里插入图片描述

组件说明
Subject主体,主体可以是任何可以与应用交互的“用户”
SecurityManager相当于SpringMVC中的DispatcherServlet或者Struts2中的FilterDispatcher;是Shiro的心脏;所有具体的交互都通过SecurityManager进行控制;它管理着所有Subject、且负责进行认证和授权、及会话、缓存的管理
Authenticator认证器,负责主体认证的,这是一个扩展点,如果用户觉得Shiro默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了
Authrizer授权器或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能
Realm可以有1个或多个Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是JDBC实现,也可以是LDAP实现,或者内存实现等等;由用户提供;注意:Shiro不知道你的用户/权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的Realm;
SessionManager如果写过Servlet就应该知道Session的概念,Session呢需要有人去管理它的生命周期,这个组件就是SessionManager;而Shiro并不仅仅可以用在Web环境,也可以用在如普通的JavaSE环境、EJB等环境;所有呢,Shiro就抽象了一个自己的Session来管理主体与应用之间交互的数据;这样的话,比如我们在Web环境用,刚开始是一台Web服务器;接着又上了台EJB服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到Memcached服务器)
SessionDAODAO大家都用过,数据访问对象,用于会话的CRUD,比如我们想把Session保存到数据库,那么可以实现自己的SessionDAO,通过如JDBC写到数据库;比如想把Session放到Memcached中,可以实现自己的Memcached SessionDAO;另外SessionDAO中可以使用Cache进行缓存,以提高性能
CacheManager缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能
Cryptography密码模块,Shiro提高了一些常见的加密组件用于如密码加密/解密的

(3)shiro名词解释

在这里插入图片描述

(4)shiro默认过滤器

当 Shiro 被运用到 web 项目时,Shiro 会自动创建一些默认的过滤器对客户端请求进行过滤。比如身份验证、授权等相关的操作。

过滤器对应的 Java 类
anonorg.apache.shiro.web.filter.authc.AnonymousFilter
authcorg.apache.shiro.web.filter.authc.FormAuthenticationFilter
authcBasicorg.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
permsorg.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
portorg.apache.shiro.web.filter.authz.PortFilter
restorg.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
rolesorg.apache.shiro.web.filter.authz.RolesAuthorizationFilter
sslorg.apache.shiro.web.filter.authz.SslFilter
userorg.apache.shiro.web.filter.authc.UserFilter
logoutorg.apache.shiro.web.filter.authc.LogoutFilter
noSessionCreationorg.apache.shiro.web.filter.session.NoSessionCreationFilter

(5)对过滤器解释说明

  1. /admins/**=anon # 表示该 uri 可以匿名访问
  2. /admins/**=auth # 表示该 uri 需要认证才能访问
  3. /admins/**=authcBasic # 表示该 uri 需要 httpBasic 认证
  4. /admins/**=perms[user:add:] # 表示该 uri 需要认证用户拥有 user:add: 权限才能访问
  5. /admins/**=port[8081] # 表示该 uri 需要使用 8081 端口
  6. /admins/**=rest[user] # 相当于 /admins/=perms[user:method],其中,method 表示 get、post、delete 等
  7. /admins/**=roles[admin] # 表示该 uri 需要认证用户拥有 admin 角色才能访问
  8. /admins/**=ssl # 表示该 uri 需要使用 https 协议
  9. /admins/**=user # 表示该 uri 需要认证或通过记住我认证才能访问
  10. /logout=logout # 表示注销,可以当作固定配置

注意:
anon,authcBasic,auchc,user 是认证过滤器。
perms,roles,ssl,rest,port 是授权过滤器

(6)常见异常

shiro全局异常 :org.apache.shiro.ShiroException
shiro常见异常分为两大类:

1. AuthencationException:

AuthenticationException 异常是Shiro在登录认证过程中,认证失败需要抛出的异常。 AuthenticationException包含以下子类:

1.1 CredentitalsException 凭证异常及子类

IncorrectCredentialsException 不正确的凭证
ExpiredCredentialsException 凭证过期

1.2 AccountException 账号异常及子类

ConcurrentAccessException 并发访问异常(多个用户同时登录时抛出)
UnknownAccountException 未知的账号
ExcessiveAttemptsException 认证次数超过限制
DisabledAccountException 禁用的账号
LockedAccountException 账号被锁定

1.3 UnsupportedTokenException 使用了不支持的Token
2. AuthorizationException:

UnauthorizedException:抛出对请求的操作或对请求的资源的访问是不允许的
UnanthenticatedException:当未完成成功认证时,执行授权操作时引发异常

(7)shiro常见标签

在这里插入图片描述

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
      <!--xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">-->
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>首页</h1>
<!--
<shiro:guest></shiro:guest>  判断用户是否是游客身份,如果是,则显示此标签内容
<shiro:user></shiro:user>  判断用户是否是登录认证之后的,如果是,则显示此标签内容
<shiro:principal></shiro:principal> 获取当前登录的用户信息
-->

<shiro:guest>
  欢迎游客访问,<a th:href="@{/toLogin}">登录</a>
</shiro:guest>
<!--从session中判断值-->
<!--<div th:if="${session.loginUser}!=null"></div>-->

<shiro:user>
  用户[<h th:text="${session.loginUser.username}"></h>]欢迎您, <a th:href="@{/users/logout}">退出</a>
</shiro:user>

<p th:text="${msg}"></p>
<hr>
<div shiro:hasPermission="user:add">
<a th:href="@{/user/add}">add</a>
</div>
<div shiro:hasPermission="user:update">
<a th:href="@{/user/update}">update</a>
</div>
</body>
</html>

二、ShiroConfig配置

1.配置Realm及多Realm的认证策略

多Realm认证策略: AuthenticationStrategy
• AuthenticationStrategy 接口的默认实现:
• FirstSuccessfulStrategy:只要有一个 Realm 验证成功即可,只返回第 一个 Realm 身份验证成功的认证信息,其他的忽略;
• AtLeastOneSuccessfulStrategy:只要有一个Realm验证成功即可,和 FirstSuccessfulStrategy 不同,将返回所有Realm身份验证成功的认证信 息;
• AllSuccessfulStrategy:所有Realm验证成功才算成功,且返回所有 Realm身份验证成功的认证信息,如果有一个失败就失败了。 • ModularRealmAuthenticator 默认是 AtLeastOneSuccessfulStrategy 策略
第一种写法:

 /**
     * 代表系统资源
     * @return
     */
    @Bean
    public UserRealm userRealm() {
        UserRealm userRealm = new UserRealm();
        userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return userRealm;
    }

    /**
     * 代表系统资源
     * @return
     */
    @Bean
    public MobileRealm mobileRealm() {
        MobileRealm mobileRealm = new MobileRealm();
        mobileRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return mobileRealm;
    }


    /**
     * 流程控制
     * @param userRealm
     * @return
     */
    @Bean
    public DefaultWebSecurityManager securityManager(UserRealm userRealm,MobileRealm mobileRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //多Realm 配置认证策略
        //AllSuccessfulStrategy所有realm都认证通过
        //FirstSuccessfulStrategy 第一个Realm认证成功,后面的realm再不认证
        //AtLeastOneSuccessfulStrategy 至少有一个realm认证通过
        securityManager.setRealms(Arrays.asList(userRealm,mobileRealm));

        //配置多Realm认证策略
        ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
        modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        modularRealmAuthenticator.setRealms(Arrays.asList(userRealm,mobileRealm));
        securityManager.setAuthenticator(modularRealmAuthenticator);

        return securityManager;
    }

第二种写法:

/***
* 配置Realm
* */
@Bean
Realm userRealm() {
    TestRealm userRealm = new TestRealm();
    return userRealm;
}
/***
 * 测试realm
 * @return
 */
@Bean
Realm testRealm() {
    return new TestRealm();
}
 
/**
 * 多Realm认证策略
 * @return
 */
@Bean
Authenticator authenticator() {
    ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
    //使用一个通过验证即可通过验证的方式
    modularRealmAuthenticator.setAuthenticationStrategy(atLeastOneSuccessfulStrategy());
    return modularRealmAuthenticator;
}
/**
 * 所有reaml全都通过才算认证通过作为策略
 * @return
 */
@Bean
AuthenticationStrategy allSuccessfulStrategy() {
    AllSuccessfulStrategy allSuccessfulStrategy = new AllSuccessfulStrategy();
    return allSuccessfulStrategy;
}
/**
 * 所有reaml一个通过就算认证通过作为策略
 * @return
 */
@Bean
AuthenticationStrategy atLeastOneSuccessfulStrategy() {
    AtLeastOneSuccessfulStrategy atLeastOneSuccessfulStrategy = new AtLeastOneSuccessfulStrategy();
    return atLeastOneSuccessfulStrategy;
    }

2.配置RedisCacheManager和SeeionManager

2.1 引入依赖

<!-- 使用RedisProperties配置类-->
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- shiro+redis 做session和缓存控制-->
<dependency>
    <groupId>org.crazycake</groupId>
    <artifactId>shiro-redis</artifactId>
    <version>3.3.1</version>
</dependency>

2.2 ShiroConfig中配置

 @Bean
 public RedisManager redisManager(){
      RedisManager redisManager = new RedisManager();
      JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
      //连接池最大量20,并发特别大时
      jedisPoolConfig.setMaxTotal(redisProperties.getJedis().getPool().getMaxActive());
      //连接池的最大剩余量15个,并发不大
      jedisPoolConfig.setMaxIdle(redisProperties.getJedis().getPool().getMaxIdle());
      //连接池初始就10个
      jedisPoolConfig.setMinIdle(redisProperties.getJedis().getPool().getMinIdle());
      JedisPool jedisPool = new JedisPool(jedisPoolConfig,redisProperties.getHost(),redisProperties.getPort(),2000,redisProperties.getPassword());
      redisManager.setJedisPool(jedisPool);
      return redisManager;
  }
/**
   * 缓存控制:shiro+redis实现
   * @param redisManager
   * @return
   */
  @Bean
  public RedisCacheManager redisCacheManager(RedisManager redisManager){
      RedisCacheManager redisCacheManager = new RedisCacheManager();
      redisCacheManager.setRedisManager(redisManager);
      //针对不同用户进行缓存
      redisCacheManager.setPrincipalIdFieldName("user");
      //用户权限信息缓存时间 1800
      redisCacheManager.setExpire(1800);
      return redisCacheManager;
  }

  /**
   * SessionDAO的作用是为Session提供CRUD并进行持久化的一个shiro组件
   * @param redisManager
   * @return
   */
  @Bean
  public RedisSessionDAO redisSessionDAO(RedisManager redisManager){
      RedisSessionDAO sessionDAO = new RedisSessionDAO();
      sessionDAO.setRedisManager(redisManager);
      sessionDAO.setSessionIdGenerator(sessionIdGenerator());
      //session在redis中保存的时间 1800
      sessionDAO.setExpire(1800);
      return sessionDAO;
  }

  @Bean
  public DefaultWebSessionManager sessionManager(RedisSessionDAO redisSessionDAO){
      DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
      sessionManager.setSessionDAO(redisSessionDAO);

      //全局会话超时时间(单位毫秒),默认30分钟1800000
      sessionManager.setGlobalSessionTimeout(600000);
      //是否开启删除无效的session对象  默认为true
      sessionManager.setDeleteInvalidSessions(true);
      //是否开启定时调度器进行检测过期session 默认为true
      sessionManager.setSessionValidationSchedulerEnabled(true);
      //设置session失效的扫描时间, 清理用户直接关闭浏览器造成的孤立会话 默认为1个小时
      sessionManager.setSessionValidationInterval(3600000);
      //取消url 后面的 JSESSIONID
      sessionManager.setSessionIdUrlRewritingEnabled(false);
      return sessionManager;
  }

3.配置securityManager

/**
     * 流程控制器
     * @param userRealm
     * @return
     */
    @Bean
    public DefaultWebSecurityManager securityManager(UserRealm userRealm,
                                                     MobileRealm mobileRealm,
                                                     CookieRememberMeManager rememberMeManager,
                                                     RedisCacheManager redisCacheManager,
                                                     DefaultWebSessionManager sessionManager,
                                                     ModularRealmAuthenticator modularRealmAuthenticator,
                                                     MyModularRealmAuthenticator myModularRealmAuthenticator
                                                     ) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //securityManager.setRealm(userRealm);
        //记住我
        securityManager.setRememberMeManager(rememberMeManager);
        //缓存管理器
        securityManager.setCacheManager(redisCacheManager);
        //session管理器
        securityManager.setSessionManager(sessionManager);
        //认证策略(realm之前)
        securityManager.setAuthenticator(modularRealmAuthenticator);
        //securityManager.setAuthenticator(myModularRealmAuthenticator);
        //多realm认证
        securityManager.setRealms(Arrays.asList(userRealm,mobileRealm));
        return securityManager;
    }

4. 配置shiroFilterFactoryBean 其实就是Filter的规则


/**
     * shiro内置请求过滤器
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean (DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //添加内置过滤器,设置拦截规则
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
        //设置登录请求页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //设置登出请求页面
        filterChainDefinitionMap.put("/logout","logout");
        //设置未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/unathorized");

        //先对系统资源进行授权访问
        filterChainDefinitionMap.put("/user/add","perms[sys:c:save]");

        //配置路径过滤器,key时ant路径,**表示多级路径,*表示一级路径,?表示一个字符
        //user过滤器表示记住我才能访问(已认证也可以访问)
        filterChainDefinitionMap.put("/index","user");
        filterChainDefinitionMap.put("/user/*","anon");
        filterChainDefinitionMap.put("/**","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }

5. 配置凭证匹配器

  @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){

        //密码加密
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置加密算法
        matcher.setHashAlgorithmName("MD5");
        //设置迭代次数 eg: 123--md5->abc--md5->xyz--md5->??? 即设置密码经过多少次MD5加密
        matcher.setHashIterations(3);
        return matcher;
    }

    /**
     * 代表系统资源
     * @return
     */
    @Bean
    public UserRealm userRealm() {
        UserRealm userRealm = new UserRealm();
        userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return userRealm;
    }

    /**
     * 代表系统资源
     * @return
     */
    @Bean
    public MobileRealm mobileRealm() {
        MobileRealm mobileRealm = new MobileRealm();
        mobileRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return mobileRealm;
    }

6. 配置RememberMe

6.1 登陆页面

<div class="layui-container">
    <div class="admin-login-background">
        <div class="layui-form login-form">
            <form class="layui-form" method="post" action="">
                <div class="layui-form-item logo-title">
                    <h1>后台登录</h1>
                </div>
                <div class="layui-form-item">
                    <label class="layui-icon layui-icon-username" ></label>
                    <input type="text" name="username" lay-verify="required" placeholder="用户名" autocomplete="off" class="layui-input" value="zkc">
                </div>
                <div class="layui-form-item">
                    <label class="layui-icon layui-icon-password" ></label>
                    <input type="password" name="password" lay-verify="required" placeholder="密码" autocomplete="off" class="layui-input" value="123456">
                </div>
                <div class="layui-form-item">
                    账号密码登录<input type="radio" name="loginType" value="User" checked />
                    手机号登录<input type="radio" name="loginType" value="Mobile" />
                </div>
                <div class="layui-form-item">
                    <!--checkbox默认值-->
                    <input type="hidden" name="rememberMe" value="false">
                    <input type="checkbox" name="rememberMe" value="true" lay-skin="primary" title="记住密码">

                </div>
                <div class="layui-form-item">
                    <button class="layui-btn layui-btn-fluid" lay-submit="" lay-filter="login">登 录</button>
                </div>
            </form>
        </div>
    </div>
</div>

6.2 登录接口

  @PostMapping("/user/login")
    @ResponseBody
    public JsonResult login(@Validated LoginDto loginDto,Model model){
        log.info("========enter method UserController-login");
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(loginDto.getUsername(), loginDto.getPassword());
        log.info("RememberMe type========"+loginDto.getRememberMe());
        //用自定义token进行登录
        //MyToken token = new MyToken(loginDto.getUsername(),loginDto.getPassword(),loginDto.getLoginType());
        if(loginDto.getRememberMe()){
            token.setRememberMe(true);
        }
        try {
            subject.login(token);
            model.addAttribute("username",token.getUsername());
            return new JsonResult();
        } catch (UnknownAccountException e) {
            return new JsonResult().error("账户不存在");
        }catch (IncorrectCredentialsException e){
            return new JsonResult().error("密码不正确");
        }
    }

6.3 ShiroConfig配置

/**
     * @return
     * 在shiro应用做了记住我功能,而这个功能在服务端通过cookie存储账号信息时,
     * 会对账号信息进行Base64加密,在加密时会创建一把密钥,密钥在服务端重启时会丢失,
     * 当我们再次通过浏览器访问服务时,因为客户端存储账号信息的cookie还是有效的,
     * 所以浏览器依旧会携带cookie到服务端,但是服务端解密cookie信息的密钥丢失,
     * 所以不能完成解密操作,就会出现异常,这种异常只会在程序重启(shiro清除session)第一次打开页面的时候出现
     */
    @Bean
    public CookieRememberMeManager cookieRememberMeManager (){
        //记住我功能,登录之后在配置时间内,关闭浏览器之后,访问配置的user过滤器的资源时不需要再认证直接可以访问的
        CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(31536000);
        cookie.setPath("/");
        rememberMeManager.setCookie(cookie);
        //指定cookie的主动设置cipherkey 加密解密密钥
        rememberMeManager.setCipherKey(Base64.getDecoder().decode(Constants.REMEMBERME_DECODE_KEY));
        return rememberMeManager;
    }

三、测试代码案例

1. shiro认证流程

• 1、首先调用 Subject.login(token) 进行登录,其会自动委托给 SecurityManager

• 2、SecurityManager 负责真正的身份验证逻辑;它会委托给 Authenticator 进行身份验证;

• 3、Authenticator 才是真正的身份验证者,Shiro API 中核心的身份 认证入口点,此处可以自定义插入自己的实现;

• 4、Authenticator 可能会委托给相应的 AuthenticationStrategy 进 行多 Realm 身份验证,默认 ModularRealmAuthenticator 会调用 AuthenticationStrategy 进行多 Realm 身份验证;

• 5、Authenticator 会把相应的 token 传入 Realm,从 Realm 获取 身份验证信息,如果没有返回/抛出异常表示身份验证失败了。此处 可以配置多个Realm,将按照相应的顺序及策略进行访问。

2.Realm的认证和授权

2.1 UserRealm

public class Constants {

    public static final String SALT = "!QAZ@WSX";
    public static final String REMEMBERME_DECODE_KEY = "6ZmI6I2j5Y+R5aSn5ZOlAA==";
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUserProfile implements Serializable {

    private static final long serialVersionUID = -6725793787701776691L;

    private User user;

    private Set<String> roles;

    private Set<String> permissions;
}
public class UserRealm extends AuthorizingRealm {
    public static final Logger log = LoggerFactory.getLogger(UserRealm.class);
    @Lazy
    @Autowired
    UserMapper userMapper;

    @Lazy
    @Autowired
    RoleService roleService;

    @Lazy
    @Autowired
    PermissionService permissionService;

    public String getName(){
        return "UserRealm";
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("============>查询角色和权限信息");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        //获取当前用户信息
        LoginUserProfile profile = (LoginUserProfile) subject.getPrincipal();
        //查询角色
        Set<String> roleNameList = roleService.getRoleNamesByUserId(profile.getUser().getId());
        //查询权限
        Set<String> permissionCodeList = permissionService.getPermissionsByUsername(profile.getUser().getUsername());
        profile.setRoles(roleNameList);
        profile.setPermissions(permissionCodeList);
        //设置当前用户的角色和权限
        info.setRoles(roleNameList);
        info.setStringPermissions(permissionCodeList);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("================enter method UserRealm-doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        LoginUserProfile profile = new LoginUserProfile();
        //查询用户
        User user = userMapper.getUserByUsername(userToken.getUsername());
        if(null == user){
            throw new UnknownAccountException("账号不存在");
        }
        profile.setUser(user);
        SecurityUtils.getSubject().getSession().setAttribute("loginUser",profile);
        //加salt返回
        ByteSource salt = ByteSource.Util.bytes(Constants.SALT);
        return new SimpleAuthenticationInfo(profile,user.getPassword(),salt,getName());
    }
}

2.2 MobileRealm

@Slf4j
public class MobileRealm extends AuthenticatingRealm {

    @Lazy
    @Autowired
    UserMapper userMapper;

    public String getName(){
        return "MobileRealm";
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("===============enter method MobileRealm-doGetAuthenticationInfo");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        LoginUserProfile profile = new LoginUserProfile();
        //查询
        User user = userMapper.getUserByPhone(userToken.getUsername());
        if(user == null){
            throw new UnknownAccountException("账户不存在");
        }
        profile.setUser(user);
        SecurityUtils.getSubject().getSession().setAttribute("loginUser",user);
        //加salt返回
        ByteSource salt = ByteSource.Util.bytes(Constants.SALT);
        return new SimpleAuthenticationInfo(profile,user.getPassword(),salt,getName());
    }
}

3.shiro的授权方式

规则:
在这里插入图片描述

(1)编程式:通过if/else授权代码块完成

if(subject.hasRole(“admin”)){有权限}else{无权限}

(2)注解式:

通过在方法上使用相应的注解来完成,没有权限将抛出相应异常
在这里插入图片描述
开启注解:

  /**
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        autoProxyCreator.setProxyTargetClass(true);
        return autoProxyCreator;
    }

注解式抛出的异常用SpringBoot统一异常处理来拦截

@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler(value = ShiroException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ErrorResult handleShiroException(ShiroException e){
        log.info("登录时异常---------->{}",e.getMessage());
        return new ErrorResult(401,e.getMessage());
    }
}

或者可以返回到指定的错误页面

@ControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String handleShiroException(Exception e){
        if(e instanceof AuthorizationException){
           return "error";
        }
        return null;
    }

(3)过滤器中配置

@Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean (DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);


        //添加内置过滤器,设置拦截规则
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
        //设置登录请求页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //设置登出请求页面
        filterChainDefinitionMap.put("/logout","logout");
        //设置未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/unathorized");

        //先对系统资源进行授权访问
        filterChainDefinitionMap.put("/user/add","perms[sys:c:save]");

        //配置路径过滤器,key时ant路径,**表示多级路径,*表示一级路径,?表示一个字符
        filterChainDefinitionMap.put("/user/*","anon");
        filterChainDefinitionMap.put("/**","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }

(4)使用标签形式

  1. 先配置加入标签使用的依赖
 <!--shiro+thymeleaf-->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>
  1. shiro配置文件中配置方言

    /**
     * 整合shiro+thymeleaf,可以使用shiro:hasPermission 等标签
     * @return
     */
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }

  1. html 标签添加
<!DOCTYPE html>
<html xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
      xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
  1. 使用shiro标签
<shiro:hasPermission name="sys:x:save">
<dd><a href="javascript:">添加订单</a></dd>
</shiro:hasPermission>

3.完整版ShiroConfig配置类

@Configuration
public class ShiroConfig {

    @Autowired
    RedisProperties redisProperties;

    /**
     * 凭证匹配器
     * @return
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        //密码加密
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //设置加密算法
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //设置迭代次数 eg: 123--md5->abc--md5->xyz--md5->??? 即设置密码经过多少次MD5加密
        hashedCredentialsMatcher.setHashIterations(3);
        return hashedCredentialsMatcher;
    }

    /**
     * 代表系统资源
     * @return
     */
    @Bean
    public UserRealm userRealm(HashedCredentialsMatcher hashedCredentialsMatcher) {
        UserRealm userRealm = new UserRealm();
        userRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return userRealm;
    }

    /**
     * 代表系统资源
     * @return
     */
    @Bean
    public MobileRealm mobileRealm(HashedCredentialsMatcher hashedCredentialsMatcher) {
        MobileRealm mobileRealm = new MobileRealm();
        mobileRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return mobileRealm;
    }

    /**
     *  多个Realm认证策略
     *  AllSuccessfulStrategy所有realm都认证通过
     *  FirstSuccessfulStrategy 第一个Realm认证成功,后面的realm再不认证
     *  AtLeastOneSuccessfulStrategy 至少有一个realm认证通过
     * @param userRealm
     * @param mobileRealm
     * @return
     */
    @Bean
    public ModularRealmAuthenticator modularRealmAuthenticator(UserRealm userRealm,MobileRealm mobileRealm){
        //配置多Realm认证策略
        ModularRealmAuthenticator modularRealmAuthenticator = new ModularRealmAuthenticator();
        modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        modularRealmAuthenticator.setRealms(Arrays.asList(userRealm,mobileRealm));
        return modularRealmAuthenticator;
    }

    /**
     * 自定义认证器
     * @return
     */
    @Bean
    public MyModularRealmAuthenticator myModularRealmAuthenticator(){
        return new MyModularRealmAuthenticator();
    }

    /**
     * @return
     * 在shiro应用做了记住我功能,而这个功能在服务端通过cookie存储账号信息时,
     * 会对账号信息进行Base64加密,在加密时会创建一把密钥,密钥在服务端重启时会丢失,
     * 当我们再次通过浏览器访问服务时,因为客户端存储账号信息的cookie还是有效的,
     * 所以浏览器依旧会携带cookie到服务端,但是服务端解密cookie信息的密钥丢失,
     * 所以不能完成解密操作,就会出现异常,这种异常只会在程序重启(shiro清除session)第一次打开页面的时候出现
     */
    @Bean
    public CookieRememberMeManager cookieRememberMeManager (){
        //记住我功能,登录之后在配置时间内,关闭浏览器之后,访问配置的user过滤器的资源时不需要再认证直接可以访问的
        CookieRememberMeManager rememberMeManager = new CookieRememberMeManager();
        SimpleCookie cookie = new SimpleCookie("rememberMe");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(31536000);
        cookie.setPath("/");
        rememberMeManager.setCookie(cookie);
        //指定cookie的主动设置cipherkey 加密解密密钥
        rememberMeManager.setCipherKey(Base64.getDecoder().decode(Constants.REMEMBERME_DECODE_KEY));
        return rememberMeManager;
    }

    /**
     * 缓存控制:比如第一次进行授权时查询数据库权限之后,接下来的操作再不用去数据库查询权限
     * @return
     */
    @Bean
    public MemoryConstrainedCacheManager cacheManager(){
        return new MemoryConstrainedCacheManager();
    }

   /**
     * 缓存控制:shiro+redis实现
     * setPrincipalIdFieldName("")这里传的值是UserRealm认证后返回的SimpleAuthenticationInfo的第一个参数的属性
     * 比如:我在Realm认证里传的LoginuserProfile对象,则在这里传对象里的user属性
     * 如果第一个参数传的是实体,则此处传的是通过该参数能唯一查到该条实体数据的参数;传实体时这里默认是该实体的id字段
     * 如果第一个参数传的是username或者其他单个参数,则这里直接用同样的参数即可
     * @param redisManager
     * @return
     */
    @Bean
    public RedisCacheManager redisCacheManager(RedisManager redisManager){
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager);
        //针对不同用户进行缓存
        redisCacheManager.setPrincipalIdFieldName("user");
        //用户权限信息缓存时间 1800
        redisCacheManager.setExpire(1800);
        return redisCacheManager;
    }

    /**
     * SessionDAO的作用是为Session提供CRUD并进行持久化的一个shiro组件
     * @param redisManager
     * @return
     */
    @Bean
    public RedisSessionDAO redisSessionDAO(RedisManager redisManager){
        RedisSessionDAO sessionDAO = new RedisSessionDAO();
        sessionDAO.setRedisManager(redisManager);
        sessionDAO.setSessionIdGenerator(sessionIdGenerator());
        //session在redis中保存的时间 1800
        sessionDAO.setExpire(1800);
        return sessionDAO;
    }

    @Bean
    public DefaultWebSessionManager sessionManager(RedisSessionDAO redisSessionDAO){
        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
        sessionManager.setSessionDAO(redisSessionDAO);

        //全局会话超时时间(单位毫秒),默认30分钟1800000
        sessionManager.setGlobalSessionTimeout(600000);
        //是否开启删除无效的session对象  默认为true
        sessionManager.setDeleteInvalidSessions(true);
        //是否开启定时调度器进行检测过期session 默认为true
        sessionManager.setSessionValidationSchedulerEnabled(true);
        //设置session失效的扫描时间, 清理用户直接关闭浏览器造成的孤立会话 默认为1个小时
        sessionManager.setSessionValidationInterval(3600000);
        //取消url 后面的 JSESSIONID
        sessionManager.setSessionIdUrlRewritingEnabled(false);
        return sessionManager;
    }

    /**
     * 流程控制器
     * @param userRealm
     * @return
     */
    @Bean
    public DefaultWebSecurityManager securityManager(UserRealm userRealm,
                                                     MobileRealm mobileRealm,
                                                     CookieRememberMeManager rememberMeManager,
                                                     RedisCacheManager redisCacheManager,
                                                     DefaultWebSessionManager sessionManager,
                                                     ModularRealmAuthenticator modularRealmAuthenticator,
                                                     MyModularRealmAuthenticator myModularRealmAuthenticator
                                                     ) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //securityManager.setRealm(userRealm);
        //记住我
        securityManager.setRememberMeManager(rememberMeManager);
        //缓存管理器
        securityManager.setCacheManager(redisCacheManager);
        //session管理器
        securityManager.setSessionManager(sessionManager);
        //认证策略(realm之前)
        securityManager.setAuthenticator(modularRealmAuthenticator);
        //securityManager.setAuthenticator(myModularRealmAuthenticator);
        //多realm认证
        securityManager.setRealms(Arrays.asList(userRealm,mobileRealm));
        return securityManager;
    }


    /**
     * shiro内置请求过滤器
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean (DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);

        //添加内置过滤器,设置拦截规则
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
        //设置登录请求页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //设置登出请求页面
        filterChainDefinitionMap.put("/logout","logout");
        //设置未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/unathorized");

        //先对系统资源进行授权访问
        filterChainDefinitionMap.put("/user/add","perms[sys:c:save]");

        //配置路径过滤器,key时ant路径,**表示多级路径,*表示一级路径,?表示一个字符
        //user过滤器表示记住我才能访问(已认证也可以访问)
        filterChainDefinitionMap.put("/index","user");
        filterChainDefinitionMap.put("/user/*","anon");
        filterChainDefinitionMap.put("/**","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }

    @Bean
    public RedisManager redisManager(){
        RedisManager redisManager = new RedisManager();
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //连接池最大量20,并发特别大时
        jedisPoolConfig.setMaxTotal(redisProperties.getJedis().getPool().getMaxActive());
        //连接池的最大剩余量15个,并发不大
        jedisPoolConfig.setMaxIdle(redisProperties.getJedis().getPool().getMaxIdle());
        //连接池初始就10个
        jedisPoolConfig.setMinIdle(redisProperties.getJedis().getPool().getMinIdle());
        JedisPool jedisPool = new JedisPool(jedisPoolConfig,redisProperties.getHost(),redisProperties.getPort(),2000,redisProperties.getPassword());
        redisManager.setJedisPool(jedisPool);
        return redisManager;
    }

    /**
     * Session ID 生成器
     *
     * @return JavaUuidSessionIdGenerator
     */
    @Bean
    public JavaUuidSessionIdGenerator sessionIdGenerator() {
        return new JavaUuidSessionIdGenerator();
    }

    /* 加入注解的使用,不加入这个注解不生效--开始 */
    /**
     *
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
    @Bean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator(){
        DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        autoProxyCreator.setProxyTargetClass(true);
        return autoProxyCreator;
    }
    /* 加入注解的使用,不加入这个注解不生效--结束 */

    /**
     * 整合shiro+thymeleaf,可以使用shiro:hasPermission 等标签
     * @return
     */
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}

4. 完整yml文件

server:
  port: 8888

spring:
  datasource:
    url: jdbc:mysql://121.41.106.140:3306/shiroDB?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    type: com.alibaba.druid.pool.DruidDataSource
  #redis配置
  redis:
    host: 121.41.106.140
    port: 6379
    password: r123456
    jedis:
      pool:
        max-wait: 2000  #连接池最大阻塞等待时间,负值表示没有限制
        max-active: 20  #连接池中的最大连接数,负值表示没有限制,默认为8
        max-idle: 8     #连接池中最大的空闲连接数
        min-idle: 0     #连接池中最小的空闲连接数

mybatis-plus:
  mapper-locations: classpath*:/mapper/**Mapper.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

5. 完整pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zjhc</groupId>
    <artifactId>springboot-shiro</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>springboot-shiro</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- shiro -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.7.1</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>5.1.47</scope>
        </dependency>
        <!-- mybatis plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>
        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.23</version>
        </dependency>
        <!--hutool工具包-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.7</version>
        </dependency>
        <!-- thymeleaf 模板-->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <!--shiro+thymeleaf-->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- shiro+redis 做session和缓存控制-->
        <dependency>
            <groupId>org.crazycake</groupId>
            <artifactId>shiro-redis</artifactId>
            <version>3.3.1</version>
        </dependency>
        <!-- Hibernate Validate-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

四、自定义认证器进行多Realm认证

1. 重写token继承UsernamePasswordToken

public class MyToken extends UsernamePasswordToken {

    private static final long serialVersionUID = -3038706751607520819L;

    private String loginType;


    public MyToken(String username, String password, String loginType) {
        super(username, password);
        this.loginType = loginType;
    }

    public String getLoginType() {
        return loginType;
    }

    public void setLoginType(String loginType) {
        this.loginType = loginType;
    }

2. 重写认证器集成ModularRealmAuthenticator

@Slf4j
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("===============进入自定义认证器MyModularRealmAuthenticator");
        this.assertRealmsConfigured();
        Collection<Realm> realms = this.getRealms();
        Collection<Realm> realmList = new ArrayList<>();
        MyToken token = (MyToken) authenticationToken;
        String loginType = token.getLoginType();
        for(Realm realm : realms){
            if(realm.getName().startsWith(loginType)){
                realmList.add(realm);
            }
        }
        if(realmList.size() == 1){
            return this.doSingleRealmAuthentication((Realm) realmList.iterator().next(),authenticationToken);
        }else{
            return this.doMultiRealmAuthentication(realmList,authenticationToken);
        }
    }
}

3. ShiroConfig中进行配置自定义认证器

    /**
     * 自定义认证器
     * @return
     */
    @Bean
    public MyModularRealmAuthenticator myModularRealmAuthenticator(){
        return new MyModularRealmAuthenticator();
    }

4. SecurityManager中进行配置

 /**
     * 流程控制器
     * @param userRealm
     * @return
     */
    @Bean
    public DefaultWebSecurityManager securityManager(UserRealm userRealm,
                                                     MobileRealm mobileRealm,
                                                     CookieRememberMeManager rememberMeManager,
                                                     RedisCacheManager redisCacheManager,
                                                     DefaultWebSessionManager sessionManager,
                                                     ModularRealmAuthenticator modularRealmAuthenticator,
                                                     MyModularRealmAuthenticator myModularRealmAuthenticator
                                                     ) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();

        //securityManager.setRealm(userRealm);
        //记住我
        securityManager.setRememberMeManager(rememberMeManager);
        //缓存管理器
        securityManager.setCacheManager(redisCacheManager);
        //session管理器
        securityManager.setSessionManager(sessionManager);
        //认证策略(realm之前)
        //securityManager.setAuthenticator(modularRealmAuthenticator);
        securityManager.setAuthenticator(myModularRealmAuthenticator);
        //多realm认证
        securityManager.setRealms(Arrays.asList(userRealm,mobileRealm));
        return securityManager;
    }

5. 登录接口

 @PostMapping("/user/login")
    @ResponseBody
    public JsonResult login(@Validated LoginDto loginDto,Model model){
        log.info("========enter method UserController-login");
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        //UsernamePasswordToken token = new UsernamePasswordToken(loginDto.getUsername(), loginDto.getPassword());
        log.info("RememberMe type========"+loginDto.getRememberMe());
        //用自定义token进行登录
        MyToken token = new MyToken(loginDto.getUsername(),loginDto.getPassword(),loginDto.getLoginType());
        if(loginDto.getRememberMe()){
            token.setRememberMe(true);
        }
        try {
            subject.login(token);
            model.addAttribute("username",token.getUsername());
            return new JsonResult();
        } catch (UnknownAccountException e) {
            return new JsonResult().error("账户不存在");
        }catch (IncorrectCredentialsException e){
            return new JsonResult().error("密码不正确");
        }
    }

6. 页面

<div class="layui-container">
    <div class="admin-login-background">
        <div class="layui-form login-form">
            <form class="layui-form" method="post" action="">
                <div class="layui-form-item logo-title">
                    <h1>后台登录</h1>
                </div>
                <div class="layui-form-item">
                    <label class="layui-icon layui-icon-username" ></label>
                    <input type="text" name="username" lay-verify="required" placeholder="用户名" autocomplete="off" class="layui-input" value="zkc">
                </div>
                <div class="layui-form-item">
                    <label class="layui-icon layui-icon-password" ></label>
                    <input type="password" name="password" lay-verify="required" placeholder="密码" autocomplete="off" class="layui-input" value="123456">
                </div>
                <div class="layui-form-item">
                    账号密码登录<input type="radio" name="loginType" value="User" checked />
                    手机号登录<input type="radio" name="loginType" value="Mobile" />
                </div>
                <div class="layui-form-item">
                    <!--checkbox默认值-->
                    <input type="hidden" name="rememberMe" value="false">
                    <input type="checkbox" name="rememberMe" value="true" lay-skin="primary" title="记住密码">

                </div>
                <div class="layui-form-item">
                    <button class="layui-btn layui-btn-fluid" lay-submit="" lay-filter="login">登 录</button>
                </div>
            </form>
        </div>
    </div>
</div>

五、统一返回处理

@Data
public class JsonResult<T> implements Serializable {

    private int code;
    private String msg;
    private T data;

    public JsonResult(){
        this.code = 200;
        this.msg = "操作成功";
    }

    public JsonResult(String msg){
        this.code = 200;
        this.msg = msg;
    }

    public JsonResult(int code,String msg){
        this.code = code;
        this.msg = msg;
    }

    public JsonResult(T data){
        this.code = 200;
        this.msg = "操作成功";
        this.data = data;
    }

    public JsonResult(T data,String msg){
        this.code = 200;
        this.msg = msg;
        this.data = data;
    }

    public JsonResult success(T data){
        JsonResult<T> result = new JsonResult<>();
        result.setCode(200);
        result.setMsg("操作成功");
        result.setData(data);
        return result;
    }

    public JsonResult success(T data,String msg){
        JsonResult<T> result = new JsonResult<>();
        result.setCode(200);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }

    public JsonResult error(String msg){
        JsonResult<T> result = new JsonResult<>();
        result.setCode(-1);
        result.setMsg(msg);
        result.setData(null);
        return result;
    }
}

六、统一异常处理

@Data
public class ErrorResult implements Serializable {

    private int code;

    private String msg;

    public ErrorResult(String msg){
        this.msg = msg;
    }

    public ErrorResult(int code, String msg){
        this.code = code;
        this.msg = msg;
    }
}

6.1 shiro使用注解权限时异常处理

6.1.1 springboot项目中解决方法

使用注解时shiroFilterFactoryBean.setUnauthorizedUrl无效,无权限或者没登录时页面不跳转,展示不友好页面。
Shiro注解模式下,访问权限注解管理的接口时,没有登录、登录失败与没有权限都是通过抛出异常的,需要用springboot统一异常处理来捕获处理

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler(value = AuthorizationException.class)
    public String handleAuthorizationException(AuthorizationException e){
        if(e instanceof UnauthorizedException){
            log.info("shiro-UnauthorizedException---------->{}",e.getMessage());
            return "redirect:/unathorized";
        }else if(e instanceof UnauthenticatedException){
            log.info("shiro-UnauthenticatedException---------->{}",e.getMessage());
            return "redirect:/toLogin";
        }
        return null;
    }

    @ExceptionHandler(value = ShiroException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ErrorResult handleShiroException(ShiroException e){
        log.info("shiro异常{}---------->{}",e,e.getMessage());
        return new ErrorResult(401,e.getMessage());
    }

    @ExceptionHandler(ValidationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResult handleValidationException(ValidationException e){
        log.info("参数校验异常------------>{}",e.getMessage());
        return new ErrorResult(400,e.getMessage());
    }

    @ExceptionHandler(value = BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResult handleMethodArgumentNotValidException(BindException e){
        /*
        筛选错误信息,错误信息有多个时,返回一个集合
         */
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        log.info("实体校验异常---------->{}",objectError.getDefaultMessage());
        return new ErrorResult(400,objectError.getDefaultMessage());
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResult handleIllegalArgumentException(IllegalArgumentException e){
        log.info("不合法的参数异常---------->{}",e.getMessage());
        return new ErrorResult(400,e.getMessage());
    }

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResult handleRuntimeException(RuntimeException e){
        log.info("运行时异常---------->{}",e.getMessage());
        return new ErrorResult(400,e.getMessage());
    }
}

6.1.2 springMVC项目中解决方法

在ShiroConfig配置文件中配置

/**
     * 解决:无权限页面不跳转,shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized") 无效
     * Shiro注解模式下,登录失败与没有权限都是通过抛出异常
     *
     * @return
     */
    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver simpleMappingExceptionResolver=new SimpleMappingExceptionResolver();
        Properties properties=new Properties();
        //这里的unauthorized 是页面,不是访问的路径
        properties.setProperty("org.apache.shiro.authz.UnauthorizedException","unathorized");
        properties.setProperty("org.apache.shiro.authz.UnauthenticatedException","unathorized");
        simpleMappingExceptionResolver.setExceptionMappings(properties);
        return simpleMappingExceptionResolver;
    }

6.2 shiro处理访问不存在的资源或者服务器异常错误

/**
     * 访问不存在的后台服务,如/userInfo/adddfdsafsafsa 这样后面随便乱打的,
     * 这种情况,依然还是返回了Whitelabel Error Page页面,我们不想看到这种效果
     * 把页面必须放在resource/static下面,不然访问不到
     * @return
     */
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
        return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
                ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/errorPage/404.html");
                ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/errorPage/500.html");
                factory.addErrorPages(error404Page,error500Page);
            }
        };
    }   

七、常见问题处理

7.1 org.crazycake.shiro.exception.SerializationException: serialize error, object=

出现这种情况是因为:SimpleByteSource没有是实现Serializable接口
解决办法:

  1. 取消authenticationCache在上面的 shiroRealm 配置中 我们开启了两个缓存:authenticationCache 和 authorizationCache 序列化失败的原因就是 因为开启了 authenticationCache 可以将 authenticationCache对应的那两行配置 删除,只缓存 authorizationCache
  2. 自定义一个类继承SimpleByteSource实现Serializable接口
    当然也可以实现ByteSource接口和Serializable接口,但是实现ByteSource接口需要实现其方法,不方便。
    自定义一个SimpleByteSource 类继承继承SimpleByteSource实现Serializable接口
public class SimpleByteSource extends org.apache.shiro.util.SimpleByteSource implements Serializable {
    private static final long serialVersionUID = 7220896367594761367L;
    public SimpleByteSource(byte[] bytes) {
        super(bytes);
    }
}

创建工具类ByteSourceUtils

public class ByteSourceUtils {
    public static ByteSource bytes(byte[] bytes){
        return new SimpleByteSource(bytes);
    }
    public static ByteSource bytes(String arg0){
        return new SimpleByteSource(arg0.getBytes());
    }
}

最后在Realm认证方法中

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("=====================enter method UserRealm-doGetAuthenticationInfo进行登陆验证");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        LoginUserProfile profile = new LoginUserProfile();
        //查询用户
        User user = userMapper.getUserByUsername(userToken.getUsername());
        if(null == user){
            throw new UnknownAccountException("账号不存在,请重试");
        }
        profile.setUser(user);
        SecurityUtils.getSubject().getSession().setAttribute("loginUser",profile);
        //加salt返回
        //ByteSource salt = ByteSource.Util.bytes(Constants.SALT);
        ByteSource salt = ByteSourceUtils.bytes(Constants.SALT);
        return new SimpleAuthenticationInfo(profile,user.getPassword(),salt,getName());
  }
  1. 将SimpleByteSource整个类 复制粘贴 给个名字 叫MyByteSource,额外实现Serializable接口,并添加无参构造器
public class MyByteSource implements ByteSource,Serializable {

    private byte[] bytes;
    private String cachedHex;
    private String cachedBase64;

    public MyByteSource() {
    }

    public MyByteSource(byte[] bytes) {
        this.bytes = bytes;
    }


    public MyByteSource(char[] chars) {
        this.bytes = CodecSupport.toBytes(chars);
    }


    public MyByteSource(String string) {
        this.bytes = CodecSupport.toBytes(string);
    }


    public MyByteSource(ByteSource source) {
        this.bytes = source.getBytes();
    }


    public MyByteSource(File file) {
        this.bytes = new MyByteSource.BytesHelper().getBytes(file);
    }


    public MyByteSource(InputStream stream) {
        this.bytes = new MyByteSource.BytesHelper().getBytes(stream);
    }

    public static boolean isCompatible(Object o) {
        return o instanceof byte[] || o instanceof char[] || o instanceof String ||
                o instanceof ByteSource || o instanceof File || o instanceof InputStream;
    }

    @Override
    public byte[] getBytes() {
        return this.bytes;
    }

    @Override
    public boolean isEmpty() {
        return this.bytes == null || this.bytes.length == 0;
    }

    @Override
    public String toHex() {
        if ( this.cachedHex == null ) {
            this.cachedHex = Hex.encodeToString(getBytes());
        }
        return this.cachedHex;
    }

    @Override
    public String toBase64() {
        if ( this.cachedBase64 == null ) {
            this.cachedBase64 = Base64.encodeToString(getBytes());
        }
        return this.cachedBase64;
    }

    @Override
    public String toString() {
        return toBase64();
    }

    @Override
    public int hashCode() {
        if (this.bytes == null || this.bytes.length == 0) {
            return 0;
        }
        return Arrays.hashCode(this.bytes);
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        if (o instanceof ByteSource) {
            ByteSource bs = (ByteSource) o;
            return Arrays.equals(getBytes(), bs.getBytes());
        }
        return false;
    }

    //will probably be removed in Shiro 2.0.  See SHIRO-203:
    //https://issues.apache.org/jira/browse/SHIRO-203
    private static final class BytesHelper extends CodecSupport {

        /**
         * 嵌套类也需要提供无参构造器
         */
        private BytesHelper() {
        }

        public byte[] getBytes(File file) {
            return toBytes(file);
        }

        public byte[] getBytes(InputStream stream) {
            return toBytes(stream);
        }
    }

}

7.2 No SecurityManager accessible to the calling code

在这里插入图片描述
原因:formAuthenticationFilter 在shiroFilterFactoryBean前面加载,而后使用
SecurityUtils.getSubject()时会报这个错,应该放后面去加载;
注意:自定义filter也应该在shiroFilter之后加载;如果将自定义的Filter在ShiroFitler之前加载,ShiroFilter 是整个 Shiro 的入口点,用于拦截需要安全控制的请求进行处理,当自定义的filter先于shiroFilter加载,而shiroFilter里又使用到该自定义filter时,就会导致调用该自定义filter进行预处理时访问不到SecurityManager
在这里插入图片描述

7.3 rememberMe时,Userinfo必须实现序列化接口

UserInfo实体类必须实现序列化接口,否则报序列化异常。因为RememberMe会将用户信息加密然后以Cookie保存
在这里插入图片描述

7.4 xxxx is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)解决

在使用shiro时,ShiroFilterFactoryBean 会依赖注入 securityManager 然后 securityManager 会注入自定义 Realm ,然后自定义Realm类里面会注入业务的service类,而那些service类包含事务,都是动态代理类。因此无法注入,大致异常为:xxxx is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
解决方法:

  1. 在字段上加@Lazy(推荐)
import org.springframework.context.annotation.Lazy;
import org.apache.shiro.realm.AuthorizingRealm;
 
public class DatabaseRealm extends AuthorizingRealm {
    @Lazy
    @Autowired
    private UserService userService;
  1. 加到构造方法的参数上
import org.springframework.context.annotation.Lazy;
import org.apache.shiro.realm.AuthorizingRealm;
public class DatabaseRealm extends AuthorizingRealm {
    private UserService userService;
	public DatabaseRealm(@Lazy @Autowired UserService userService){
		this.userService = userService;
	}
}
  1. 使用hutool工具类下的SpringUtil
  @Override
 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
     UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
     **MUserService userService = SpringUtil.getBean(MUserService.class);**
     MUser user = userService.getOneUser(userToken.getUsername());
     if(user == null){
         throw new UnknownAccountException("账户不存在");
     }
     return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
 }
  1. 在Shiro框架中注入Bean时,不使用@Autowire,使用ApplicationContextRegister.getBean()方法,手动注入bean。保证该方法只有在程序完全启动运行时,才被注入

7.5 事务失效的解决方法

由于shiro的bean先于Spring事务将userService实例化了,结果导致spring事务初始化时好无法扫描到该bean,导致这个bean上没有绑定事务,导致事务无效,报错如下:
在这里插入图片描述

  1. 在字段上加@Lazy(推荐)
import org.springframework.context.annotation.Lazy;
import org.apache.shiro.realm.AuthorizingRealm;
public class DatabaseRealm extends AuthorizingRealm {
    @Lazy
    @Autowired
    private UserService userService;
  1. orm映射框架的Mapper类,不是由Spring生成初始化,只是交给Spring管理,不会影响Spring bean的初始化
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
}
  1. 在service实现层的类或者public方法上添加@Transactionl注解
SpringBoot整合Shiro Shiro是一个开源的Java安全框架,它提供了身份认证、授权、加密和会话管理等功能,可以帮助我们快速地构建安全可靠的应用程序。 阅读详情

相关推荐

QT | QT打包生成单个EXE文件

1.以release方式运行程序 2.在release文件夹中找到.exe文件 如果没有找到exe,可能是因为在项目中勾选了shadow build,你可以在构建目录中找到exe 3.将exe放在一个新建的文件夹中,因为待会儿会生成很多dll文件 4.点击电脑左下角搜索QT,打开Qt 5.8 for Desktop (MinGQW 5.3.0 32bit) 5.进入刚刚新建的文件夹,输入wi...

⊳ideal world⊲~ヽ(゚︺゚)Hi 1243

SpringBoot与Shiro整合详解

Apache Shiro 是一个Java的安全(权限)框架 ------- 和SpringSecurity一样是安全框架 2. Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在JavaSe环境. 3. Shiro 可以完成: 认证,授权,加密,会话管理,Web集成,缓存等...

Zero摄氏度的博客 2508

Splunk CVE-2018-11409认证绕过漏洞深度解析

Splunk作为主流企业级日志分析平台,其Web管理接口的认证机制直接关系到整个安全运营体系的可信边界。CVE-2018-11409本质上是REST API路由层会话校验缺失引发的未授权访问问题,根源在于`/en-US/splunkd/__raw/`路径绕过了splunkweb与splunkd之间的信任链验证,导致配置文件、用户哈希、App源码等敏感信息明文泄露。该漏洞凸显了Web接口权限模型设计失守的风险,尤其在默认配置未加固、HTTPS未启用、初始密码未修改的生产环境中危害急剧放大。结合vulfocus

weixin_30875157的博客 605

SpringBoot之整合Shiro(最详细)

1.SpringBoot整合Shiro思路 2. 环境搭建 2.1 创建项目 2.2 引入依赖 pom.xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency&g

emgexgb_sef的博客 2015

结构光三维重建(一)条纹结构光三维重建

在近景三维重建领域,结构光技术可以说是应用最广泛的,尤其在工业领域。该技术目前具有高精度和无视弱纹理等优点,但复杂的室外环境还是会对该技术造成一定程度的干扰。目前用的比较多的结构光分别两大类:线结构光以及条纹结构光。接下来我先来简单介绍一下条纹结构光三维重建,事实上,条纹结构光的原理与双目立体匹配是非常相似的。...

AAAA202012的博客 1万+

Xilinx ZYNQ 7000学习笔记二(FSBL代码分析启动-汇编代码)

Xilinx ZYNQ 7000学习笔记

u011116085的博客 4255

【问题解决】org.crazycake.shiro.exception.SerializationException

org.apache.shiro.session.UnknownSessionException: org.crazycake.shiro.exception.SerializationException: serialize error, object=org.apache.shiro.session.mgt.SimpleSession,id=login_token_059abe24-c...

小猿备忘录 4415

crazyswarm无人机集群搭建笔记(一)资料索引

crazyswarm无人机搭建笔记:资料收集

Coco_range的博客 814

Springboot2.1 + Redis + Shiro集群

感谢博主:这个名字想了很久对本文shiro整合redis部分提供很多参考还有解答 crazycake官网:http://alexxiyang.github.io/shiro-redis/ Eclipse安装springboot插件:https://www.cnblogs.com/zjdxr-up/p/8617242.html 我用的mars 4.5.2 所以我下的tools是这个:http:...

elysion_k的博客 5289

从亚稳态到稳定传输:深入解析CDC跨时钟域同步的核心技术与设计实践

本文深入解析了CDC(跨时钟域同步)技术的核心问题与解决方案,重点探讨了亚稳态现象及其危害,详细介绍了同步器设计、MTBF计算方法以及单bit和多bit信号同步的实战技巧。通过Verilog代码示例和工程实践案例,帮助读者掌握从亚稳态到稳定传输的关键技术,提升数字电路设计的可靠性。

weixin_32822843的博客 253

成对使用离轴抛物面反射镜的设计

成对使用离轴抛物面反射镜的设计

weixin_72050316的博客 642

shiro SimpleSession的序列化

不知道有没有人会问这个序列化它,能有什么用。 假如你和我一样从一个有历史背景的项目中 “脱颖而杀出一条血路” 的话,你可能会觉得这个有用【笑哭了的表情】 项目用的 Shiro,权限 + session 强绑定的技术背景,应用服务通过依赖 shiro sdk 而多点访问 redis 读取session 的业务现状(redisSessionDao 技术兄弟们对这个可能不陌生),多点访问 redis 意味着session 协议升级,与应用服务迭代的相互影响,以及可能会存在小机率的事务性问题(说到这终于想起

weixin_38989369的博客 2783

【图像超分】论文复现:CVPR 2024 | 轻量化超分 | 窗口注意力改进 | CAMixerSR的Pytorch源码复现,跑通源码,获得指标和超分结果,计算复杂度,架构梳理拆解,逐行注释!

本文介绍了超分辨率重建方法CAMixerSR的代码实现与运行指南。文章亮点包括:完整跑通源码获取PSNR/SSIM指标和可视化结果;详细解析模型架构与关键代码注释,帮助快速复现基线模型。实验部分提供了测试配置文件和训练设置说明,支持2K/4K/8K大图像超分和x2/x4轻量化超分。环境依赖PyTorch和BasicSR框架,数据集包含DIV2K等常用基准。测试结果与论文指标一致,可视化输出保存至指定目录。训练配置可自定义数据集路径、GPU数量等参数。该实现突出了CAMixerSR在降低W-MSA复杂度方面的

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 447

Springboot + Shiro完美案列

Springboot + Shiro完美案列1.创建Springboot项目2.添加依赖3.配置数据库4.创建项目结构5.项数据库插入数据6.配置访问页面7.测试 本来之前没想过写博客后来看见,一个大佬写了好几篇不错的博客,感悟挺多的我也决定写博客(其实前面不知道该写啥),正好看见一个不错的安全框架Shiro就自己摸索着写了这个不错的案列,Shiro是干什么的有什么用处不知道的小伙伴可也自行百度,...

weixin_43959028的博客 2589

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

SpringBoot+Shiro初步整合

这两天尝试了一下Shiro的权限管理,理论性的东西就不去赘述了,这种还是比较多的,这里记录一下一个快速的整合,这里我按照我自己书写流程,来记录。 第一步:建立数据库,这个数据库可以使用自己喜欢的搭建方式,hibernate或者Mybatis,或者直接原生的也是可以的。                这里按照最简单的来:用户表(userId--用户id,username--用户名,passwor...

tzc_xyh的博客 433

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Springboot使用shiro

一、什么叫Aop Aop 作为面向对象编程的一种补充,广泛应用于处理一些具有横切性质的系统级服务器,如事务管理,安全检查,缓存检查,对象池管理等 Aop 实现的关键就在于代理的实现,代理分为动态代理与静态代理.动态代理是指在运行时借助JDK动态代理、CGLIB等在内存中“临时”生成Aop动态代理类,被称为运行时增强。 ...

qq_38345598的博客 4112

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

Springboot整合shiro

是一款主流的Java安全框架,不依赖任何容器,可以运行在Java SE和Java EE项目中,它的主要作用是对访问系统的用户进行身份认证、授权、会话管理、加密等操作。Shiro 就是用来解决安全管理的系统化框架。Shiro是基于session的身份认证和访问控制框架。RBAC是Role-Based Access Control(基于角色的访问控制)的缩写。它是一种广泛应用于安全管理中的访问控制模型。RBAC模型通过授予用户不同的角色,并将角色与权限进行关联,来管理对资源的访问。

chao的博客 2800

【SpringBoot框架篇】15.使用shiro对web应用进行权限认证

使用shiro对web应用进行权限认证

皓亮君的博客 3074

SpringBoot之Shiro使用

SpringBoot之Shiro使用 一、Shiro简介 1、Shiro 是什么? Apache Shiro 是 Java 的一个安全(权限)框架。 Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境,也可以用在 JavaEE 环境。 Shiro 可以完成:认证、授权、加密、会话管理、与Web 集成、缓存等。 下载地址 官网:http://shiro.apache.org/ github:https://github.com/apache/shiro 2

Daylight629博客 1000

Shiro安全框架详解及springboot使用示例

目录一、认识Shiro1、什么是Shiro?2、有哪些功能?3、Shiro架构(外部)4、Shiro架构(内部) 一、认识Shiro 1、什么是Shiro? Apache Shiro 是一个Java 的安全(权限)框架。 Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环 境。 Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等。 2、有哪些功能? Authentication:身份认证、登录,验证用户是不是拥有相应的身份; Aut

weixin_46822367的博客 4373

springboot使用shiro

使用shiro重点在于两个类 1.ShiroConfiguration 下面这个方法是设置访问时,如果想直接访问index以及后面的界面必须先登录,所以会自动跳转到login界面 @Bean public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager){ System.out.println("Shi

malachi95的博客 2841

SpringBoot-Shiro的使用

一、什么是Shiro 权限体系在现代软件应用中有着非常重要的地位。一个应用如果没有权限体系都会显着这个系统“特别不安全”,无论是传统的MIS系统还是互联网项目出于对业务数据和应用自身的安全,都会设置自己的安全策略。 目前市场上专门的Java权限框架有Apache Shiro 和 Spring Security。相较于Spring Security 来说 Shiro更加老牌。学习好Shiro对于以后市场上在出现新型权限框架的学习能带来很大便利。因为权限的概念是不变的,变得是框架的实现方式。当然了,对于第一次学

qq_42861526的博客 2364

shiro+springboot使用demo小案例

shiro+springboot使用 1、什么是shiro shiro一款java安全框架,提供认证、授权、会话管理、加密等功能。 2、核心组件 subject:表示当前操作用户(包含用户、第三方进程、后台账户);代表了当前用户的安全操作 SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过该组件来管理内部组件实例,并通过它来提供安全管理...

qq_38316726的博客 2656

shiro在springboot中的使用

Shiro 一. Shiro权限 什么是权限控制: 忽略特别细的概念,比如权限能细分很多种,功能权限,数据权限,管理权限等 理解两个概念:用户和资源,让指定的用户,只能操作指定的资源(CRUD) 初学javaweb时怎么做 Filter接口中有一个doFilter方法,自己编写好业务Filter,并配置对哪个web资源进行拦截后 如果访问的路径命中对应的Filter,则会执行doFilter()方法,然后判断是否有权限进行访问对应的资源 /api/user/info?id=1 public

sylvia_lily的博客 2831

springboot整合shiro 配置详解及原理分析

springboot整合shiro+jwt实现前后端分离认证授权前言问题ShiroFilter什么是ShiroFilterSecurityManager什么是SecurityManager?ShiroConfig写在前面的话:ShiroConfig类:CustomRealm类:shiroConfig原理 前言 最近搞了下shiro安全框架,网上找了好多篇博客,感觉要么都是复制粘贴,要么就是错误百出。至于稍微讲解一下为什么要这么做,就更别说了。这篇文章就教大家如何将 Shiro 整合到 SpringBoot

fl8545的博客 2052
上一篇: 记:前后端分离项目中@IgnoreToken注解的使用
下一篇: SpringBoot + jwt 详解+使用案例
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一位不知名民工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址