springboot整合Shiro的步驟

1.創建一個springboot項目

選中web和thymeleaf

1.1新建index.html

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

1.2創建一個controller

package com.yao.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class MyController {
 
    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,Shiro");
        return "index";
    }
}

一定要記住shiro的三大對象

1.subject:用戶

2.SecurityManager:管理所有用戶

3.Realm:連接數據

1.3導入整合用的依賴包

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.4.1</version>
</dependency>

1.4創建一個config(ShiroConfig),並編寫他

package com.yao.config;
 
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class ShiroConfig {
 
    //ShiroFilterFactoryBean
 
    //DefaultWebSecurityManager
 
    //創建 realm 對象,這個realm對象需要自定義
     
}

1.5創建自己的一個realmconfig,也就是在config中創建另外一個配置類UserRealm

package com.yao.config;
 
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
 
//自定義的 UserRealm
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;
    }
}

1.6將UserRealm註冊到ShiroConfig裡面去,是我們自己寫的這個類被spring托管

1.7新建兩個測試頁面並重新寫一下index頁面

add.html

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

update.html

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

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>首頁</h1>
    <p th:text="${msg}"></p>
    <hr>
<a th:href="@{/user/add}" rel="external nofollow" >add</a> | <a th:href="@{/user/update}" rel="external nofollow" >update</a>
</body>
</html>

1.8編寫controller層

package com.yao.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class MyController {
 
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "index";
    }
 
@RequestMapping("/user/add")
public String add(){
return "user/add";
    }
 
@RequestMapping("/user/update")
public String update(){
return "user/update";
    }
}

1.9添加過濾器

還是在shiroconfig中加入:

//添加Shiro的內置過濾器
/*
            anon:無需認證就可以訪問
            authc:必須認證瞭才能通過
            user:必須擁有記住我功能才能用
            perms:擁有對某個資源的權限才可以訪問
            role:擁有某個角色權限才能訪問
         */
Map<String,String> filterMap = new LinkedHashMap<>();
//        filterMap.put("/user/add","authc");
//        filterMap.put("/user/update","authc");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//設置登錄的請求
bean.setLoginUrl("/toLogin");
return bean;

這裡希望沒有認證就從add和update跳到login頁面因此還要寫一個login頁面和改寫controller

controller層:

@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}

login頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登錄</title>
</head>
<body>
<form>
    <p>用戶名: <input type="text" name="username"></p>
    <p>密碼:<input type="text" name="password"></p>
    <p><input type="submit"></p>
</form>
</body>
</html>

1.10上面已經完成瞭頁面攔截的功能接下來實現用戶認證的工作

login.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>登錄</title>
</head>
<body>
<p th:text="${msg}" ></p>
<form th:action="@{/login}">
    <p>用戶名: <input type="text" name="username"></p>
    <p>密碼:<input type="text" name="password"></p>
    <p><input type="submit"></p>
</form>
</body>
</html>

controller:

@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);// 執行登陸的方法,如果沒有異常就ok瞭
return "index";
    } catch (UnknownAccountException e) {
model.addAttribute("msg","用戶名錯誤");
return "login";
    } catch (IncorrectCredentialsException e){
model.addAttribute("msg"," 密碼錯誤");
return "login";
    }
}

UserRealm:

//認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("認證。。。");
 
//用戶名,密碼 數據庫中取
String name = "root";
String password = "123456";
 
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
 
if(!userToken.getUsername().equals(name)){
return null;//它這裡會自動拋出前面的用戶名錯誤的異常
}
//密碼認證不讓你做,它自己做,他不讓你接觸密碼
return new SimpleAuthenticationInfo("",password,"");
    }
}

直接測試即可發現以上功能基本實現。

package com.yao.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class MyController {
 
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "index";
    }
}

2.springboot整合mybatis

2.1導入依賴

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.12</version>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>

2.2編寫配置文件application.yml

spring:
  datasource:
    username: root
    password: 892095368llq
    #?serverTimezone=UTC解決時區的報錯
    url: jdbc:mysql://localhost:3306/yao?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
 
    #Spring Boot 默認是不註入這些屬性值的,需要自己綁定
    #druid 數據源專有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
 
    #配置監控統計攔截的filters,stat:監控統計、log4j:日志記錄、wall:防禦sql註入
    #如果允許時報錯  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #則導入 log4j 依賴即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

2.3編寫配置文件application.properties並新建mapper文件夾

application.properties

mybatis.type-aliases-package=com.yao.pojo
mybatis.mapper-locations=classpath:mapper/*.xml

2.4創建pojo層,並配置lombok

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.10</version>
</dependency>

編寫一個User.java

package com.yao.pojo;
 
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
 
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}

2.4創建mapper層,並寫出相對應的mapper接口和resources中的對應的mapper實現

UserMapper接口

package com.yao.mapper;
 
import com.yao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
 
@Repository
@Mapper
public interface UserMapper {
    public User queryUserByName(String name);
}
mapper。xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 
<mapper namespace="com.yao.mapper.UserMapper">
<select id="queryUserByName" parameterType="String" resultType="User">
    select * from user where name = #{name}
</select>
 
</mapper>

UserService.interface

package com.yao.service;
 
import com.yao.pojo.User;
 
public interface UserService {
    public User queryUserByName(String name);
}
UserServiceImpl.java
package com.yao.service;
 
import com.yao.mapper.UserMapper;
import com.yao.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service
public class UserServiceImpl implements UserService{
 
    @Autowired
    UserMapper userMapper;
 
    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }
}

2.6在test中測試

package com.yao;
 
import com.yao.service.UserService;
import com.yao.service.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
 
@SpringBootTest
class ShiroSpringbootApplicationTests {
    @Autowired
    UserServiceImpl userService;
 
    @Test
    void contextLoads() {
        System.out.println(userService.queryUserByName("幺幺"));
 
    }
 
}

測試成功,繼續寫

2.7更改UserRealm

package com.yao.config;
 
import com.yao.pojo.User;
import com.yao.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
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;
 
//自定義的 UserRealm
public class UserRealm extends AuthorizingRealm {
 
    @Autowired
    UserService userService;
 
    //授權
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授權。。。");
        return null;
    }
    //認證
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("認證。。。");
 
 
 
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //連接真實數據庫
        User user = userService.queryUserByName(userToken.getUsername());
        if (user==null){
            return null;
        }
 
        //密碼認證不讓你做,它自己做,他不讓你接觸密碼
        return new SimpleAuthenticationInfo("",user.getPwd(),"");
    }
}

2.8添加密碼加密

//還有一個md5加密,集成瞭hashcode是不可逆的
        //比如你的密碼是123456
//        md5(123456,32) = e10adc3949ba59abbe56e057f20f883e
//        md5(123456,16) = 49ba59abbe56e057
        //MD5鹽值加密e10adc3949ba59abbe56e057f20f883eusername
        //密碼認證不讓你做,它自己做,他不讓你接觸密碼
        return new SimpleAuthenticationInfo("",user.getPwd(),"");

2.9請求授權實現

==============

2.10綁定thymeleaf

package com.yao.mapper;

import com.yao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface UserMapper {
public User queryUserByName(String name);
}

以上就是springboot整合Shiro的步驟的詳細內容,更多關於springboot整合Shiro的資料請關註WalkonNet其它相關文章!

推薦閱讀: