基于crudapi后端Java SDK二次開發(fā)之API認(rèn)證和鑒權(quán)(二)
回顧
通過上一篇文章 基于crudapi后端Java SDK二次開發(fā)之環(huán)境搭建(一)的介紹,后臺(tái)API已經(jīng)搭建完成。RBAC權(quán)限模型中介紹了用戶和權(quán)限相關(guān)內(nèi)容,本文主要介紹API集成中認(rèn)證和鑒權(quán)相關(guān)內(nèi)容。
背景
實(shí)際項(xiàng)目中,為了保證數(shù)據(jù)安全,API需要認(rèn)證才可以訪問,本文主要介紹三種API認(rèn)證方式,基于Spring Security框架實(shí)現(xiàn), 包括Cookie,Basic Auth,JWT令牌Token。
Swagger api文檔
https://demo.crudapi.cn/swagger-ui.html
默認(rèn)用戶名密碼:
superadmin/1234567890
Cookie
登錄api
登錄成功后,瀏覽器自動(dòng)處理cookie并識(shí)別登錄狀態(tài),適合web訪問場(chǎng)景,方便快捷!
POST https://demo.crudapi.cn/api/auth/login
accept: application/json
content-type: application/x-www-form-urlencoded
username: superadmin
password: 1234567890
JWT令牌Token
登錄成功后,記錄TOKEN,每次發(fā)送請(qǐng)求之前,設(shè)置一下即可,后臺(tái)會(huì)解析TOKEN并識(shí)別用戶,并判斷是否具有權(quán)限,適合手機(jī)移動(dòng)端訪問場(chǎng)景,有效期比cookie長(zhǎng)!
登錄api
POST https://demo.crudapi.cn/api/auth/jwt/login
accept: application/json
content-type: application/x-www-form-urlencoded
username: superadmin
password: 1234567890

獲取JWT Token
從請(qǐng)求返回的頭里面獲取token字段內(nèi)容,格式為Bearer XXXXX
設(shè)置JWT token
設(shè)置Type為Bearer Token
Bearer XXXXX和XXXX兩種格式都可以,后臺(tái)自動(dòng)識(shí)別

查看Authorization
請(qǐng)求頭Authorization字段自動(dòng)識(shí)別為:Bearer XXXXX

基本認(rèn)證Basic Auth
直接采用戶名和密碼的方式,適合任何簡(jiǎn)單處理的場(chǎng)景,要注意安全問題。
設(shè)置
設(shè)置Type為Basic Auth
輸入用戶名密碼即可

查看Authorization
請(qǐng)求頭Authorization字段自動(dòng)識(shí)別為: Basic c3VwZXJhZG1pbjoxMjM0NTY3ODkw,其中c3VwZXJhZG1pbjoxMjM0NTY3ODkw為superadmin:1234567890的Base64編碼。

其它接口
注銷登錄
GET https://demo.crudapi.cn/api/auth/logout
創(chuàng)建用戶接口
POST https://demo.crudapi.cn/api/business/user
{
"name": "testuser",
"username": "testuser",
"password": "testuser",
"enabled": true,
"accountNonExpired": true,
"accountNonLocked": true,
"credentialsNonExpired": true,
"roleLines": [{
"name": "業(yè)務(wù)數(shù)據(jù)角色",
"role": {
"id": 20,
"name": "業(yè)務(wù)數(shù)據(jù)角色",
},
"roleId": 20
}]
}
curl示例
查詢序列號(hào)
curl -u 'superadmin:1234567890' -X GET -H 'Content-Type: application/json' 'https://demo.crudapi.cn/api/metadata/sequences/1'
curl -H 'Authorization:Basic c3VwZXJhZG1pbjoxMjM0NTY3ODkw' -X GET -H 'Content-Type: application/json' 'https://demo.crudapi.cn/api/metadata/sequences/1'
查詢序列號(hào)
curl -u 'superadmin:1234567890' -X POST -H 'Content-Type: application/json' -d '{"currentTime":false,"sequenceType":"STRING","minValue":1,"maxValue":999999999,"nextValue":1,"incrementBy":1,"name":"orderCode","caption":"訂單流水號(hào)","format":"SO_%9d"}' 'https://demo.crudapi.cn/api/metadata/sequences'
導(dǎo)入EXCEL數(shù)據(jù)
curl -u 'superadmin:1234567890' -F "file=@product.xlsx" "https://demo.crudapi.cn/api/business/product/import"
小結(jié)
本文主要介紹了API集成三種方式,在實(shí)際應(yīng)用中,根據(jù)具體業(yè)務(wù)場(chǎng)景選擇最佳方式即可!