SpringBoot与Shiro整合-权限管理

Subject :用户主体(把操作交给SecurityManager)
SecurityManager:安全管理器(关联Realm)
Realm :shiro连接数据的桥梁

依赖

shiro依赖

     <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.3.2</version>
            </dependency>

thymeleaf整合shiro权限标签

    <!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
            <dependency>
                <groupId>com.github.theborakompanioni</groupId>
                <artifactId>thymeleaf-extras-shiro</artifactId>
                <version>2.0.0</version>
            </dependency>

整合Mybatis

dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

配置

创建UserController.java

@RequestMapping("/login")
        public String login(String name,String password,boolean rememberMe, Model model) {

             //1、获取subject
            Subject subject = SecurityUtils.getSubject();

            //2、封装用户数据
            UsernamePasswordToken token = new UsernamePasswordToken(name,password,rememberMe);

            //3、执行登录方法
            try {
                //交给Realm处理--->执行它的认证方法
                subject.login(token);
                //登录成功
                return "redirect:/testThymeleaf";
            }catch (UnknownAccountException e){
                //登录失败:用户名不存在
                model.addAttribute("msg","用户名不存在");
                return "user/login";
            }catch (IncorrectCredentialsException e){
                //登录失败:密码错误
                model.addAttribute("msg","密码错误");
                return "user/login";
            }
        }

创建UserRealm.java

package com.brewin.shiro.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.brewin.shiro.domain.User;
import com.brewin.shiro.service.UserService;

public class UserRealm extends AuthorizingRealm{
    @Autowired
    private UserService userService;
    //授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        // TODO Auto-generated method stub
        System.out.println("执行授权逻辑");
        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加资源的授权字符串
//        info.addStringPermission("user:update");

        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        //System.out.println(subject.getPrincipal());
        User dbUser = userService.findById(user.getId());
       // info.addStringPermission("user:add");
        info.addStringPermission(dbUser.getPerms());
        return info;
    }
//认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // TODO Auto-generated method stub
        System.out.println("执行认证逻辑");
           //编写shiro判断逻辑,判断用户名和密码
        UsernamePasswordToken token  =  (UsernamePasswordToken)authenticationToken;

        User user = userService.findByName(token.getUsername());

        //1、判断用户名
        if(user == null){
            //用户名不存在
            return null; //shiro底层会抛出UnKnowAccountException
        }

        //2、判断密码, 这里的user是principal
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }

}

分为认证与授权
创建ShiroConfig.java

@Configuration
public class ShiroConfig {
    //创建ShiroFileterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean=new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //添加shiro内置过滤器
        /**
         * anno:无需认证(登录)可以访问
         * authc:必须认证才可以访问
         * user:如果使用rememberMe的功能可以直接访问
         * perms:该资源必须得到资源权限才可以访问
         * role:该资源必须得到角色权限才可以访问
         */

        Map<String,String> filterMap = new LinkedHashMap<String,String>();
        //配置记住我或认证通过可以访问的地址
        filterMap.put("/testThymeleaf", "user");



        //设置放行页面
        filterMap.put("/testThymeleaf","anon");
        filterMap.put("/login","anon");

        //授权过滤器
        filterMap.put("/add","perms[user:add]");
        filterMap.put("/update","perms[user:update]");
        filterMap.put("/*", "authc");

        //拦截后默认跳转到login.jsp,修改跳转页面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        //设置未授权提示页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/noAuth");


        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    //创建DefaultWebSecurityManager
    @Bean("securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm) {
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        //关联Realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    //创建Realm
    @Bean(name="userRealm")
    public UserRealm getRealm() {
        return new UserRealm();
    }

    /**
     * 配置ShiroDialect,用于thymeleaf和shiro标签配合使用
     */
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

    /**
     2   * cookie对象;
     3   * rememberMeCookie()方法是设置Cookie的生成模版,比如cookie的name,cookie的有效时间等等。
     4   * @return
     5  */
     @Bean
     public SimpleCookie rememberMeCookie(){
       //System.out.println("ShiroConfiguration.rememberMeCookie()");
       //这个参数是cookie的名称,对应前端的checkbox的name = rememberMe
       SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
       //<!-- 记住我cookie生效时间30天 ,单位秒;-->
       simpleCookie.setMaxAge(259200);
       return simpleCookie;
     }

        /**
        * cookie管理对象;
        * rememberMeManager()方法是生成rememberMe管理器,而且要将这个rememberMe管理器设置到securityManager中
        * @return
       */
        @Bean
        public CookieRememberMeManager rememberMeManager(){
               //System.out.println("ShiroConfiguration.rememberMeManager()");
               CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
               cookieRememberMeManager.setCookie(rememberMeCookie());
               //rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位)
               cookieRememberMeManager.setCipherKey(Base64.decode("2AvVhdsgUs0FSA3SDFAdag=="));
               return cookieRememberMeManager;
         }

}

ShiroDialect与thymeleaf标签配合使用,可仅显示授权页面

创建test.html页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${title}"></h1>
<div shiro:hasPermission="user:add">
    进入用户添加功能:<a th:href="@{/add}">用户添加</a><br>
</div>
<div shiro:hasPermission="user:update">
    进入用户更新功能:<a th:href="@{/update}">用户更新</a>
</div>
<a href="/toLogin">登录</a>
</body>
</html>
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!