能否在Ballerina服务的资源级别定义预期scopes?
在资源级别定义OAuth2 Scopes的方法
当然可以在资源级别定义预期的OAuth2 scopes,不必局限于服务级别配置。在Ballerina中,你可以通过资源的@http:ResourceConfig注解单独为每个HTTP资源指定所需的scopes,实现更细粒度的权限控制。
实现方式
在资源的配置注解里,添加auth配置项并指定oauth2的scopes列表即可。资源级别的scopes设置会覆盖服务级别的全局配置,优先级更高。
代码示例对比
服务级别定义Scopes(原BBE示例方式)
import ballerina/http; import ballerina/oauth2; listener http:Listener securedEP = new(9090, secureSocket = { keyStore: { path: "../resource/path/to/keystore.p12", password: "password" } } ); @http:ServiceConfig { auth: [ { oauth2: { issuer: "https://localhost:9443/oauth2/token", scopes: ["read", "write"] } } ] } service /api on securedEP { resource function get users() returns http:Ok|http:Unauthorized { return http:Ok { body: "User list" }; } resource function post users() returns http:Created|http:Unauthorized { return http:Created { body: "User created" }; } }
资源级别定义Scopes
import ballerina/http; import ballerina/oauth2; listener http:Listener securedEP = new(9090, secureSocket = { keyStore: { path: "../resource/path/to/keystore.p12", password: "password" } } ); // 服务级别仅配置OAuth2基础信息,不指定全局scopes @http:ServiceConfig { auth: [ { oauth2: { issuer: "https://localhost:9443/oauth2/token" } } ] } service /api on securedEP { // 仅允许具备"read"权限的请求访问该资源 @http:ResourceConfig { auth: [ { oauth2: { scopes: ["read"] } } ] } resource function get users() returns http:Ok|http:Unauthorized { return http:Ok { body: "User list" }; } // 仅允许具备"write"权限的请求访问该资源 @http:ResourceConfig { auth: [ { oauth2: { scopes: ["write"] } } ] } resource function post users() returns http:Created|http:Unauthorized { return http:Created { body: "User created" }; } // 要求同时具备"read"和"write"权限才能访问 @http:ResourceConfig { auth: [ { oauth2: { scopes: ["read", "write"] } } ] } resource function put users/[string userId]() returns http:Ok|http:Unauthorized { return http:Ok { body: string.format("User %s updated", userId) }; } }
通过这种方式,你可以根据不同资源的访问需求,精准控制每个资源所需的OAuth2权限范围。
内容的提问来源于stack exchange,提问作者Kavindu Gimhan Zoysa
相关产品推荐
相关产品推荐

