ballerina 学习十九 安全编程

时间:2023-12-25 09:30:37

ballerina 内部提供了几种常用的安全开发模型,token 认证(jwt) basic auth

jwt 安全

  • 参考代码
import ballerina/http;
http:AuthProvider jwtAuthProvider = {
scheme:"jwt",
issuer:"ballerina",
audience: "ballerina.io",
certificateAlias: "ballerina",
trustStore: {
path: "${ballerina.home}/bre/security/ballerinaTruststore.p12",
password: "ballerina"
}
};
endpoint http:SecureListener ep {
port: 9090,
authProviders:[jwtAuthProvider],
secureSocket: {
keyStore: {
path: "${ballerina.home}/bre/security/ballerinaKeystore.p12",
password: "ballerina"
},
trustStore: {
path: "${ballerina.home}/bre/security/ballerinaTruststore.p12",
password: "ballerina"
}
}
};
@http:ServiceConfig {
basePath: "/hello",
authConfig: {
authentication: { enabled: true }
}
}
service<http:Service> echo bind ep {
@http:ResourceConfig {
methods: ["GET"],
path: "/sayHello",
authConfig: {
scopes: ["hello"]
}
}
hello(endpoint caller, http:Request req) {
http:Response res = new;
res.setPayload("Hello, World!!!");
_ = caller->respond(res);
}
}
  • 访问&&效果
curl -vk -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.\
eyJzdWIiOiJiYWxsZXJpbmEiLCJpc3MiOiJiYWxsZXJpbmEiLCJleHAiOjI4MTg0MTUwMTksIm\
lhdCI6MTUyNDU3NTAxOSwianRpIjoiZjVhZGVkNTA1ODVjNDZmMmI4Y2EyMzNkMGMyYTNjOWQi\
LCJhdWQiOlsiYmFsbGVyaW5hIiwiYmFsbGVyaW5hLm9yZyIsImJhbGxlcmluYS5pbyJdLCJzY2\
9wZSI6ImhlbGxvIn0.bNoqz9_DzgeKSK6ru3DnKL7NiNbY32ksXPYrh6Jp0_O3ST7WfXMs9WVk\
x6Q2TiYukMAGrnMUFrJnrJvZwC3glAmRBrl4BYCbQ0c5mCbgM9qhhCjC1tBA50rjtLAtRW-JTR\
pCKS0B9_EmlVKfvXPKDLIpM5hnfhOin1R3lJCPspJ2ey_Ho6fDhsKE3DZgssvgPgI9PBItnkip\
Q3CqqXWhV-RFBkVBEGPDYXTUVGbXhdNOBSwKw5ZoVJrCUiNG5XD0K4sgN9udVTi3EMKNMnVQaq\
399k6RYPAy3vIhByS6QZtRjOG8X93WJw-9GLiHvcabuid80lnrs2-mAEcstgiHVw" \
https://localhost:9090/hello/sayHello

没有jwt token 的
ballerina 学习十九  安全编程
包含jwt 的请求
ballerina 学习十九  安全编程

参考资料

https://ballerina.io/learn/by-example/secured-service-with-jwt.html
https://jwt.io/