• SpringBoot 整合Shiro、thymeleaf


    参考 SpringBoot最新教程IDEA版通俗易懂

    1、pom

            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.7.0</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.12</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.3</version>
            </dependency>
            <dependency>
                <groupId>com.github.theborakompanioni</groupId>
                <artifactId>thymeleaf-extras-shiro</artifactId>
                <version>2.0.0</version>
            </dependency>
    

    2、ShiroConfig

    @Configuration
    public class ShiroConfig {
    
        /**
         * ShiroFilterFactoryBean
         */
        @Bean
        public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
            ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
            //设置安全管理器
            bean.setSecurityManager(securityManager);
            //设置内部拦截器
            Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
            filterChainDefinitionMap.put("/user/add", "perms[user:add]");
            filterChainDefinitionMap.put("/user/update", "perms[user:update]");
            filterChainDefinitionMap.put("/unauthor", "anon");
            filterChainDefinitionMap.put("/user/**", "authc");
            bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
            bean.setLoginUrl("/toLogin");
            bean.setUnauthorizedUrl("/unauthor");
            return bean;
        }
    
        /**
         * DefaultWebSecurityManager
         */
        @Bean(name = "securityManager")
        public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm) {
            DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
            //关联
            securityManager.setRealm(userRealm);
            return securityManager;
        }
    
        /**
         * getUserRealm
         */
        @Bean(name = "userRealm")
        public UserRealm getUserRealm() {
            return new UserRealm();
        }
    
        /**
         * 用来整合thymeleaf-extras-shiro
         */
        @Bean
        public ShiroDialect getShiroDialect() {
            return new ShiroDialect();
        }
    }
    
    

    3、UserRealm

    //自定义的UserReal
    public class UserRealm extends AuthorizingRealm {
        @Autowired
        UserService userService;
    
        //授权
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            System.out.println("执行了->授权doGetAuthorizationInfo");
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            Subject subject = SecurityUtils.getSubject();
            User currentUser = (User) subject.getPrincipal();
            info.addStringPermission(currentUser.getPerms());
            return info;
        }
    
        //认证
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            System.out.println("执行了->认证doGetAuthenticationInfo");
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            User user = userService.getUserByName(token.getUsername());
            if (user == null) {
                return null;
            }
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            session.setAttribute("loginUser", user);
            return new SimpleAuthenticationInfo(user, token.getPassword(), "");
        }
    }
    

    4、IndexController

    @Controller
    public class IndexController {
    
        @RequestMapping({"/", "index"})
        public String toIndex(Model model) {
            model.addAttribute("msg", "hello,shiro");
            return "index";
        }
    
        @RequestMapping("/user/add")
        @RequiresPermissions("user:add")
        public String toAdd() {
            return "user/add";
        }
    
        @RequestMapping("/user/update")
        @RequiresPermissions("user:update")
        public String toUpdate() {
            return "user/update";
        }
    
        @RequestMapping("/toLogin")
        public String toLogin() {
            return "login";
        }
    
        @RequestMapping("/unauthor")
        public String toUnauthor() {
            return "unauthor";
        }
    
        @RequestMapping("/login")
        public String login(String username, String password, Model model) {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                subject.login(token);
                return "index";
            } catch (UnknownAccountException e) {
                model.addAttribute("msg", "用户名错误");
                return "login";
            } catch (IncorrectCredentialsException e) {
                model.addAttribute("msg", "密码错误");
                return "login";
            }
        }
    }
    

    5、Index.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org"
          xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
          xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
    <head>
        <meta charset="UTF-8">
        <title>Index</title>
    </head>
    <body>
    <h1>首页</h1>
    <p th:text="${msg}"></p>
    <hr>
    
    <div th:if="session.loginUser==null">
        <a th:href="@{/toLogin}">登录</a>
    </div>
    
    <div shiro:hasPermission="user:add">
        <a th:href="@{user/add}">user/add</a>
    </div>
    
    <div shiro:hasPermission="user:update">
        <a th:href="@{user/update}">user/update</a>
    </div>
    
    </body>
    </html>
    
  • 相关阅读:
    Debian8搭建LEMP环境
    ProjectManager Beta 7 项目管理器发布
    我的Linux软件集
    修改/home内子目录的名字
    Nginx配置特定二级域名
    Debian8 安装wordpress博客
    LinuxMint18使用单独分区作为Home挂载点
    LinuxMint18配置Grub2默认启动操作系统
    《失恋33天》从绝境中走出来的故事
    爱的世界很拥挤,写在读《爱,就这么简单》之后
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/14514726.html
Copyright © 2020-2023  润新知