Token令牌 Redis 案例

關注 “弋凡”(YiFan)微信公衆號吧 記錄簡單筆記 做你的最愛
SpringBoot 整合 Redis 看之前文章

Token 是什麼?

token 專業術語爲 令牌,更通俗來說就相當於暗號,一般用於身份驗證的時候,用token更加的安全,

Token 怎麼用?

一般通過ajax發送請求,服務器接收請求去驗證用戶名和密碼,然後返回給客戶端一串字符串(token),客戶端接收這個token把它存在Cookie 或者Local Storage中
客戶端每次請求資源的時候需要攜帶這個token,服務器去接收這個token然後去驗證,成功則返回請求需要的數據

Token 存在 Redis

1,導入依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.2.6.RELEASE</version>
</dependency>

2,編寫 application.properties

# redis 配置
spring.redis.host=127.0.0.1
spring.redis.port=6379

server.port=999
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
spring.thymeleaf.cache = false
# 實體類的包掃描--- 這裏使用了 MybatisPlus
mybatis-plus.type-aliases-package =com.yifan.pojo

3,添加 RedisConfig 以及

封裝好的 RedisUtil(之前文章有敘述)

4,編寫Controller

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yifan.pao.Result;
import com.yifan.pojo.User;
import com.yifan.service.UserService;
import com.yifan.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("index")
    public String index(){
        return "index";
    }

    @GetMapping({"/","/login"})
    public String login(){
        return "login";
    }

    @GetMapping("getInfoToken")
    @ResponseBody
    public String getinfo(HttpServletRequest request){
        String token = request.getHeader("token");
        System.err.println("token ---> "+token);
        long expire = redisUtil.getExpire(token);
        System.err.println("expire ---> "+redisUtil.getExpire(token));
        if(expire > 0L){
            return "ok";
        }else {
            return "error";
        }
    }
    @PostMapping("toindex")
    @ResponseBody
    public Result index(@RequestParam String name , @RequestParam String password){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getName,name).eq(User::getPassword,password);
        User one = userService.getOne(wrapper);
        if(one != null ){
            String token = UUID.randomUUID()+"";
            redisUtil.set(token,one,30000L);
            return new Result(one ,token);
        } else {
          return null ;
        }
    }
}

5,這裏的 Result是封裝的返回結果類

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {
    private T object;
    private String data;
}

6,前端頁面 一個簡單的登錄頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登錄頁面</title>
</head>
<body>
<h4>登錄</h4>
<p> <span>name:</span> <input type="text" id="name"></p>
<p> <span>password:</span> <input type="text" id="password"></p>
<p><input type="button" value="login" class="login"></p>
<p><input type="button" value="token login" class="tokenlogin"></p>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
    $(function () {
        $(".tokenlogin").click(function () {
            $.ajax({
                type: "get",
                url: "getInfoToken",
                headers:{"token":localStorage.token},
                success: function (res) {
                    console.log("-->res "+res);
                    if(res == "ok"){
                        // 跳轉 controller 中的 index 請求
                        window.location.href = "index";
                    }
                }
            })
        });
        $(".login").click(function () {
            $.ajax({
                type: "post",
                url: "toindex",
                data: {name:$("#name").val(), password:$("#password").val()},
                dataType: "json",
                success: function (res) {
                    // 本地存儲這個token
                    localStorage.token=res.data;
                    if(res !=null){
                        window.location.href = "index";
                    }
                }
            })
        })
    })
</script>
</html>

7,登錄成功頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
	<h3>登錄成功了</h3>
</body>

</html>

8,效果

在這裏插入圖片描述
end —

快來關注“弋凡”微信公衆號吧

快來關注“弋凡”微信公衆號把

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章