Springboot配置Shiro+Thymleaf+mybatis整合

  1   3 pom.xml
  6 <?xml version="1.0" encoding="UTF-8"?>
  7 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  8          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  9     <modelVersion>4.0.0</modelVersion>
 10     <parent>
 11         <groupId>org.springframework.boot</groupId>
 12         <artifactId>spring-boot-starter-parent</artifactId>
 13         <version>2.2.1.RELEASE</version>
 14         <relativePath/> <!-- lookup parent from repository -->
 15     </parent>
 16     <groupId>com.jerry</groupId>
 17     <artifactId>springboot-shirotest</artifactId>
 18     <version>0.0.1-SNAPSHOT</version>
 19     <name>springboot-shirotest</name>
 20     <description>Demo project for Spring Boot</description>
 21 
 22     <properties>
 23         <java.version>1.8</java.version>
 24     </properties>
 25 
 26     <dependencies>
 27 
 28         <!-- shiro和thymeleaf整合-->
 29         <dependency>
 30             <groupId>com.github.theborakompanioni</groupId>
 31             <artifactId>thymeleaf-extras-shiro</artifactId>
 32             <version>2.0.0</version>
 33         </dependency>
 34 
 35         <!--
 36         Subject
 37         SecurityManager
 38         Realm 连接数据
 39         -->
 40 
 41         <!-- shiro整合Spring的包 -->
 42      
 43         <dependency>
 44             <groupId>com.alibaba</groupId>
 45             <artifactId>druid</artifactId>
 46             <version>1.1.10</version>
 47         </dependency>
 48 
 49         <dependency>
 50             <groupId>com.alibaba</groupId>
 51             <artifactId>druid-spring-boot-starter</artifactId>
 52             <version>1.1.10</version>
 53         </dependency>
 54 
 55     <!--整合Mybatis-->
 56 
 57         <dependency>
 58             <groupId>org.mybatis.spring.boot</groupId>
 59             <artifactId>mybatis-spring-boot-starter</artifactId>
 60             <version>2.1.1</version>
 61         </dependency>
 62 
 63         <dependency>
 64             <groupId>mysql</groupId>
 65             <artifactId>mysql-connector-java</artifactId>
 66         </dependency>
 67 
 68         <dependency>
 69             <groupId>org.apache.shiro</groupId>
 70             <artifactId>shiro-spring</artifactId>
 71             <version>1.4.1</version>
 72         </dependency>
 73 
 74         <dependency>
 75             <groupId>log4j</groupId>
 76             <artifactId>log4j</artifactId>
 77             <version>1.2.17</version>
 78         </dependency>
 79 
 80 
 81         <dependency>
 82             <groupId>org.springframework.boot</groupId>
 83             <artifactId>spring-boot-starter-web</artifactId>
 84         </dependency>
 85       <!--整合thymeleaf-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
add

 

 86         <dependency>
 87             <groupId>org.thymeleaf</groupId>
 88             <artifactId>thymeleaf-spring5</artifactId>
 89         </dependency>
 90 
 91         <dependency>
 92             <groupId>org.thymeleaf.extras</groupId>
 93             <artifactId>thymeleaf-extras-java8time</artifactId>
 94         </dependency>
 95 
 96         <dependency>
 97             <groupId>org.springframework.boot</groupId>
 98             <artifactId>spring-boot-starter-test</artifactId>
 99             <scope>test</scope>
100             <exclusions>
101                 <exclusion>
102                     <groupId>org.junit.vintage</groupId>
103                     <artifactId>junit-vintage-engine</artifactId>
104                 </exclusion>
105             </exclusions>
106         </dependency>
107     </dependencies>
108 
109     <build>
110         <plugins>
111             <plugin>
112                 <groupId>org.springframework.boot</groupId>
113                 <artifactId>spring-boot-maven-plugin</artifactId>
114             </plugin>
115         </plugins>
116     </build>
117 
118 </project>
119 
120      

自定义Realm文件:

package com.jerry.config;

import com.jerry.pojo.User;
import com.jerry.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;
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    //权限设置:AuthorizationInfo
    @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;
    }

    //验证设置:AuthenrizationInfo
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("访问了:doGetAuthenticationInfo");
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String username = token.getUsername();
        User user = userService.getUserByName(username);
        String realname = user.getUsername();
        if(user==null){
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("user",user);
        //盐值
        /*ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername());*/
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), "");
        return simpleAuthenticationInfo;
    }
}
Userrealm

ShiroConfig

package com.jerry.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
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.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    /*
     * 密码校验规则HashedCredentialsMatcher
     * 这个类是为了对密码进行编码的 ,
     * 防止密码在数据库里明码保存 , 当然在登陆认证的时候 ,
     * 这个类也负责对form里输入的密码进行编码
     * 处理认证匹配处理器:如果自定义需要实现继承HashedCredentialsMatcher
        作者:贪挽懒月
        链接:https://www.jianshu.com/p/7716951f4d7f
        来源:简书
        著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
     */
    @Bean("hashedCredentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //指定加密方式为md5
        credentialsMatcher.setHashAlgorithmName("MD5");
        //加密次数
        credentialsMatcher.setHashIterations(1024);
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }

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

        Map<String,String > FilterChainDefinitionMap = new LinkedHashMap<>();
        //添加shiro的内置过滤器
        /**
         *  anon:无需认证就可以访问
         *  authc:必须认证了才可以访问
         *  user:必须拥有 记住我功能才能使用
         *  perms:拥有对某个的权限才能访问
         *  role:拥有某个角色的权限才能访问
         */
        bean.setLoginUrl("/toLogin");
        //先给角色设置权限,再
        FilterChainDefinitionMap.put("/user/add","perms[user:add]");
        FilterChainDefinitionMap.put("/user/update","perms[user:update]");
        FilterChainDefinitionMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(FilterChainDefinitionMap);
        return bean;
    }

    @Bean("securityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //1、第一步,自定义realm
    @Bean("userRealm")
    public UserRealm userRealm(){
        UserRealm userRealm = new UserRealm();
        return userRealm;
    }

    //整合ShiroDialect
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }


}
ShiroConfig

add.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
add.html

update.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>
View Code

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml" xmlns:shiro="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<hr>

    <div th:if="${session.user==null}">
        <a th:href="@{/toLogin}">登录</a>
    </div>




<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>
index.html

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="${msg}" style="color:red"></p>
<form th:action="@{/login}">
    <p>用户名 <input type="text" name="username"></p>
    <p>密码:<input type="text" name="password"></p>
    <p><input type="submit" value="提交"></p>
</form>

</body>
</html>

error.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Error
</body>
</html>

 

posted @ 2019-12-06 22:07  L丶小瑞  阅读(385)  评论(0)    收藏  举报