SpringBoot+JWT+SpringSecurity+MybatisPlus實現Restful鑑權腳手架

若圖片查看異常,請前往掘金查看:http://www.javashuo.com/article/p-qdyybyfx-du.htmljava

前言

JWT(json web token)的無狀態鑑權方式,愈來愈流行。配合SpringSecurity+SpringBoot,能夠實現優雅的鑑權功能。mysql

關於SpringBoot+ Security的講解,能夠參考我以前的文章:https://www.toutiao.com/i6704647082659021319/nginx

爲了減小重複造輪子的工做量,方便你們複製和參考,我把一個完整的SpringBoot+JWT+SpringSecurity+Mybatis-Plus開發的項目,放到本人的github上,方便本身的同時也方便他人。git

原創聲明

本文發佈於掘金號【Happyjava】。Happy的掘金地址:https://juejin.im/user/5cc2895df265da03a630ddca,Happy的我的博客:(http://blog.happyjava.cn)[http://blog.happyjava.cn]。歡迎轉載,但須保留此段聲明。github

源碼獲取

github地址,參考文末便可。web

項目實現的功能

一、整合了好用方便的Mybatis-plusspring

二、整合了JWTsql

三、整合了Spring Security數據庫

簡單演示

配置攔截和放行的路徑json

未登陸請求

會被攔截返回401。這個返回的內容用戶能夠自定義便可

登陸

登陸成功後訪問須要登陸的接口

這裏成功請求到了數據。

經過註解獲取當前 登陸的用戶

項目部署

數據庫準備

創建數據庫test,建表以下:

CREATE TABLE `admin` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

建表以後,自行插入用戶名密碼。

修改配置文件applicatoin.properties

把數據密碼等配置修改正確

spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 須要手寫mapper打開此配置
mybatis-plus.mapper-locations=classpath:mappers/*.xml
# jwt的密鑰
jwt.secret.key=happyjava1234214214asfasfasfasdf
# jwt過時時間
jwt.token.expired=360000

也可自定義jwt的加密密鑰和token過時時間

啓動項目

啓動項目便可經過接口進行測試

源碼地址

https://github.com/Happy4Java/hello-springboot

關注公衆號領資料

搜索公衆號【Happyjava】,回覆【電子書】和【視頻】,便可獲取大量優質電子書和大數據、kafka、nginx、MySQL等視頻資料

關注Happyjava公衆號

相關文章
相關標籤/搜索