ASK-SDK Python:如何同时使用提醒与邮政编码权限?
如何在Alexa技能中同时管理提醒和邮政编码权限
当前代码仅通过consent_token判断是否存在权限,无法区分具体是提醒还是邮政编码权限。要同时管理这两种权限,可按以下步骤实现:
1. 同时请求多个权限
修改权限请求指令,在permissionScopes中同时包含提醒和邮政编码的权限范围:
directive_response = handler_input.response_builder.add_directive( SendRequestDirective( name="AskFor", payload={ "@type": "AskForPermissionsConsentRequest", "@version": "2", "permissionScopes": [ { "permissionScope": "alexa::alerts:reminders:skill:readwrite", "consentLevel": "ACCOUNT" }, { "permissionScope": "alexa::profile:postal_code:read", "consentLevel": "ACCOUNT" } ] }, token="reminder_postal_code_permission" ) ).response
2. 处理权限授权回调
用户完成授权操作后,Alexa会发送Connections.Response事件到技能,其中包含用户同意的权限列表。需要添加专门的处理器来捕获这个事件,并将已授权的权限保存到持久化存储:
from ask_sdk_core.dispatch_components import AbstractRequestHandler from ask_sdk_core.utils import is_type class ConnectionsResponseHandler(AbstractRequestHandler): def can_handle(self, handler_input): return is_type(handler_input.request_envelope.request, "Connections.Response") def handle(self, handler_input): request = handler_input.request_envelope.request # 提取用户授予的权限列表 granted_permissions = request.payload.get("grantedPermissions", []) # 保存到用户持久化属性,供后续检查使用 persistent_attrs = handler_input.attributes_manager.persistent_attributes persistent_attrs["granted_permissions"] = granted_permissions handler_input.attributes_manager.save_persistent_attributes() # 根据授权情况生成响应话术 if not granted_permissions: speech = "你未授予任何权限,部分功能将无法使用。" elif len(granted_permissions) == 2: speech = "所有权限已授予,功能可以正常使用。" else: speech = "部分权限已授予,对应功能可正常使用。" return handler_input.response_builder.speak(speech).response
3. 检查特定权限
在需要使用对应功能时,从持久化存储中读取已授权的权限列表,检查目标权限是否存在,而非仅判断consent_token是否存在:
def check_permission(handler_input, target_scope): """检查指定权限是否已授权""" persistent_attrs = handler_input.attributes_manager.persistent_attributes granted_scopes = [p["permissionScope"] for p in persistent_attrs.get("granted_permissions", [])] return target_scope in granted_scopes # 使用示例:检查提醒权限 if not check_permission(handler_input, "alexa::alerts:reminders:skill:readwrite"): # 此处可发起提醒权限的单独请求 pass # 检查邮政编码权限 if not check_permission(handler_input, "alexa::profile:postal_code:read"): # 此处可发起邮政编码权限的单独请求 pass
补充:解析JWT令牌获取权限(可选)
如果不想依赖持久化存储,也可以解析consent_token的JWT payload,其中包含授权的权限范围。但需注意验证令牌的合法性(确保是Alexa签发),避免安全风险。解码后的令牌payload中,scope字段会列出已授权的权限。
内容的提问来源于stack exchange,提问作者CauseYNot
相关产品推荐
相关产品推荐

