HarmonyOS鸿蒙Next中如何实现JWT权限验证
HarmonyOS鸿蒙Next中如何实现JWT权限验证,JSON Web Token(JWT)是一种开放标准(RFC 7519),用于在网络应用间安全地传输信息。这些信息以 JSON 对象的形式编码在令牌中,可以被数字签名。使用 HMAC 算法或者 RSA 公私钥对来签名。
HarmonyOS鸿蒙Next JWT的组成
JWT 的三个部分依次如下。
Header(头部)
Payload(负载)
Signature(签名)
Arkts 请求接口获取Token 验证Token
import axios, { AxiosError, AxiosResponse } from '@ohos/axios'
@Entry
@Component
struct JwtPage {
@State message: string = 'Hello World';
@State token: string = ""
bearerAuthLogin=()=> {
axios.get('http://192.168.2.46:3000/api/v2/login').then((response: AxiosResponse) => {
console.log(response.data["token"])
this.token = response.data["token"]
})
}
bearerAuthGetAddress=()=> {
// 设置请求URL和参数
const url = 'http://192.168.2.46:3000/api/v2/address';
// 发送请求
axios.get(url, {
headers: {
Authorization: `Bearer ${this.token}`,
}
})
.then((response: AxiosResponse) => {
console.log("bearerAuthGetAddress返回的数据")
console.log(JSON.stringify(response.data));
})
.catch((error: AxiosError) => {
if (error.response) {
// 请求已发出,服务器返回状态码不在2xx范围内
console.error('Error response:', error.response.status, error.response.data);
} else if (error.request) {
// 请求已发出但没有收到响应
console.error('No response:', error.request);
} else {
// 发送请求时出错
console.error('Request error:', error.message);
}
});
}
build() {
Column() {
Button() {
Text("JWt Auth Login").fontSize(20).fontColor(Color.White)
}.width('80%')
.height('140lpx')
.margin({
top: 20
}).onClick(this.bearerAuthLogin)
Button() {
Text("JWt Auth GetAddress").fontSize(20).fontColor(Color.White)
}.width('80%')
.height('140lpx')
.margin({
top: 20
})
.onClick(this.bearerAuthGetAddress)
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.height('100%')
.width('100%')
}
}
更多关于HarmonyOS鸿蒙Next中如何实现JWT权限验证的实战教程也可以访问 https://www.itying.com/category-93-b0.html