AGC云存储权限管理:精细化控制鸿蒙5文件访问
一、AGC云存储权限体系概述
- 权限模型架构
AGC云存储采用三层权限控制体系:
graph TD
A[全局权限] --> B[存储桶权限]
B --> C[文件/对象权限]
- 权限类型详解
权限类型 说明 适用场景
读取 查看/下载文件 公开资源访问
写入 上传/修改文件 用户内容提交
删除 移除文件 内容管理
管理 权限配置 管理员操作
二、环境配置与初始化 - 添加依赖配置
在entry/build.gradle中:
dependencies {
// AGC核心
implementation 'com.huawei.agconnect:agconnect-core-harmony:1.6.5.300'
// 云存储
implementation 'com.huawei.agconnect:agconnect-storage-harmony:1.6.5.300'
// 认证服务
implementation 'com.huawei.agconnect:agconnect-auth-harmony:1.6.5.300'
}
2. 初始化云存储服务
创建StorageManager.ets:
import agconnect from '@hw-agconnect/core';
import storage from '@hw-agconnect/storage';
export class StorageManager {
private static instance: StorageManager | null = null;
private storage: storage.AGCStorage;
private constructor() {
// 初始化实例
this.storage = storage.storage(agconnect.instance());
}
public static getInstance(): StorageManager {
if (!StorageManager.instance) {
StorageManager.instance = new StorageManager();
}
return StorageManager.instance;
}
// 获取存储引用
getStorageRef(): storage.AGCStorage {
return this.storage;
}
}
三、基础权限配置实践
- 设置全局权限规则
在AGC控制台配置storage.rules:
{
"rules": {
"public": {
"read": true,
"write": "auth != null"
},
"private": {
"read": "auth != null",
"write": "auth != null"
},
"user_uploads/${userId}": {
"read": true,
"write": "auth != null && auth.uid == userId"
}
}
}
2. 权限验证代码示例
// 在StorageManager中添加
async checkPermission(path: string, operation: 'read' | 'write' | 'delete'): Promise
try {
const ref = this.storage.reference(path);
const rules = await ref.getRules();
switch (operation) {
case 'read':
return rules.read;
case 'write':
return rules.write;
case 'delete':
return rules.delete;
default:
return false;
}
} catch (error) {
console.error('权限检查失败:', error);
return false;
}
}
四、精细化权限控制实现
-
用户隔离存储空间
// 获取用户专属存储引用
async getUserStorage(userId: string): storage.StorageReference {
// 验证当前用户权限
const currentUser = agconnect.auth().currentUser;
if (!currentUser || currentUser.uid !== userId) {
throw new Error('无权访问该用户存储空间');
}return this.storage.reference(
user_uploads/${userId});
}
// 示例:上传用户头像
async uploadUserAvatar(userId: string, fileUri: string): Promise
try {
const userStorage = await this.getUserStorage(userId);
const avatarRef = userStorage.child('avatar.jpg');
// 设置自定义元数据
const metadata = {
customMetadata: {
'owner': userId,
'uploadTime': new Date().toISOString()
}
};
// 执行上传
await avatarRef.putFile(fileUri, metadata);
return await avatarRef.getDownloadURL();
} catch (error) {
console.error('头像上传失败:', error);
throw error;
}
}
2. 基于角色的访问控制
// 角色权限配置
const ROLE_PERMISSIONS = {
'admin': {
read: true,
write: true,
delete: true
},
'editor': {
read: true,
write: true,
delete: false
},
'viewer': {
read: true,
write: false,
delete: false
}
};
// 验证角色权限
async verifyRolePermission(path: string, role: string, operation: string): Promise
const rolePermission = ROLE_PERMISSIONS[role];
if (!rolePermission) return false;
// 获取实际权限设置
const ref = this.storage.reference(path);
const rules = await ref.getRules();
// 检查角色权限是否满足要求
if (operation === 'read') {
return rules.read && rolePermission.read;
} else if (operation === 'write') {
return rules.write && rolePermission.write;
} else if (operation === 'delete') {
return rules.delete && rolePermission.delete;
}
return false;
}
五、安全规则动态配置
-
客户端安全规则验证
// 在StorageManager中添加
async validateSecurityRules(path: string, operation: string): Promise{
const ref = this.storage.reference(path);
const rules = await ref.getRules();const auth = agconnect.auth().currentUser;
const context = {
auth: auth ? {
uid: auth.uid,
email: auth.email,
emailVerified: auth.emailVerified
} : null,
resource: {
path: path
}
};let allowed = false;
switch (operation) {
case 'read':
allowed = await this.evaluateRule(rules.read, context);
break;
case 'write':
allowed = await this.evaluateRule(rules.write, context);
break;
case 'delete':
allowed = await this.evaluateRule(rules.delete, context);
break;
}if (!allowed) {
throw new Error(无权执行${operation}操作);
}
}
private async evaluateRule(rule: any, context: any): Promise
// 实际项目中应使用规则引擎评估
if (typeof rule === 'boolean') return rule;
if (typeof rule === 'string') {
// 简单模拟规则评估
if (rule === 'auth != null') return !!context.auth;
if (rule.includes('auth.uid')) {
const expectedUid = rule.split('==')[1].trim().replace(/'/g, '');
return context.auth?.uid === expectedUid;
}
}
return false;
}
2. 服务端规则管理API
import http from '@ohos.net.http';
// 更新存储规则
async updateStorageRules(newRules: string): Promise
const httpRequest = http.createHttp();
const token = await agconnect.auth().currentUser?.getToken();
try {
await httpRequest.request(
'https://storage-api.cloud.huawei.com/v1/rules',
{
method: 'PUT',
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
extraData: JSON.stringify({ rules: newRules })
}
);
console.log('存储规则更新成功');
} catch (error) {
console.error('规则更新失败:', error);
throw error;
}
}
六、实战案例:企业文档管理系统
-
文件上传与权限设置
// 在StorageManager中添加
async uploadCompanyDocument(
companyId: string,
filePath: string,
options: {
isPublic: boolean,
allowedDepartments: string[]
}
): Promise{
// 验证当前用户权限
await this.validateSecurityRules(
companies/${companyId}/documents,
'write'
);// 创建文件引用
const docRef = this.storage.reference(
companies/${companyId}/docs/${Date.now()}_${filePath.split('/').pop()}
);// 设置自定义元数据
const metadata = {
customMetadata: {
'owner': agconnect.auth().currentUser?.uid,
'company': companyId,
'isPublic': String(options.isPublic),
'allowedDepartments': JSON.stringify(options.allowedDepartments),
'uploadTime': new Date().toISOString()
}
};// 执行上传
await docRef.putFile(filePath, metadata);
return await docRef.getDownloadURL();
} -
安全下载实现
// 在StorageManager中添加
async downloadDocument(documentPath: string): Promise{
// 验证下载权限
const ref = this.storage.reference(documentPath);
const metadata = await ref.getMetadata();// 检查文档权限
const isPublic = metadata.customMetadata?.isPublic === 'true';
const allowedDepts = JSON.parse(metadata.customMetadata?.allowedDepartments || '[]');if (!isPublic) {
// 获取用户部门信息(假设从用户属性获取)
const user = agconnect.auth().currentUser;
const userDept = user?.getUserInfo()?.department;if (!userDept || !allowedDepts.includes(userDept)) { throw new Error('无权访问该文档'); }}
// 获取下载URL
return await ref.getDownloadURL();
}
七、权限变更监听与响应 -
设置权限变更监听器
// 在StorageManager中添加
setupPermissionListeners() {
// 监听存储规则变化
this.storage.on('rulesUpdated', (event) => {
console.log('存储规则已更新:', event.path);
this.refreshLocalPermissions();
});// 监听用户认证状态变化
agconnect.auth().onAuthStateChanged((user) => {
console.log('用户状态变化,刷新权限:', user?.uid);
this.refreshLocalPermissions();
});
}
private refreshLocalPermissions() {
// 实际应用中应更新本地权限缓存
console.log('刷新本地权限设置');
}
2. 实时权限检查组件
@Component
struct PermissionGuard {
@Prop path: string;
@Prop operation: string;
@Prop fallback: () => void;
@State hasPermission: boolean = false;
@State loading: boolean = true;
private storageManager = StorageManager.getInstance();
aboutToAppear() {
this.checkPermission();
}
async checkPermission() {
this.loading = true;
try {
this.hasPermission = await this.storageManager.checkPermission(
this.path,
this.operation
);
} catch (error) {
console.error('权限检查错误:', error);
this.hasPermission = false;
} finally {
this.loading = false;
}
}
build() {
Column() {
if (this.loading) {
LoadingProgress()
.width(20)
.height(20)
} else if (!this.hasPermission) {
Button('无权访问,点击返回')
.onClick(this.fallback)
} else {
Slot()
}
}
}
}
八、调试与问题排查
-
权限调试工具类
// 在StorageManager中添加
async debugPermissions(path: string) {
const ref = this.storage.reference(path);
const rules = await ref.getRules();
const metadata = await ref.getMetadata();console.group(
存储权限调试: ${path});
console.log('基本规则:', {
read: rules.read,
write: rules.write,
delete: rules.delete
});console.log('文件元数据:', metadata.customMetadata);
const auth = agconnect.auth().currentUser;
console.log('当前用户:', auth ? {
uid: auth.uid,
email: auth.email
} : '未登录');console.groupEnd();
} -
常见问题解决方案
问题1:权限拒绝错误
// 在StorageManager中添加错误处理
async safeUpload(path: string, fileUri: string) {
try {
const ref = this.storage.reference(path);
return await ref.putFile(fileUri);
} catch (error) {
if (error.code === 'storage/unauthorized') {
console.error('权限不足,尝试刷新令牌...');
await agconnect.auth().currentUser?.refreshToken();
return await this.safeUpload(path, fileUri);
}
throw error;
}
}
问题2:跨域访问问题
配置CORS规则:
async setCorsRules(rules: Array<{
origin: string[],
method: string[],
responseHeader: string[],
maxAgeSeconds: number
}>): Promise
const httpRequest = http.createHttp();
const token = await agconnect.auth().currentUser?.getToken();
try {
await httpRequest.request(
'https://storage-api.cloud.huawei.com/v1/cors',
{
method: 'PUT',
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
extraData: JSON.stringify({ cors: rules })
}
);
} catch (error) {
console.error('CORS规则设置失败:', error);
throw error;
}
}
总结
通过本文的学习,你已经掌握了在HarmonyOS 5应用中实现AGC云存储精细化权限管理的完整方案:
权限体系架构:理解全局、存储桶和对象级别的权限控制
安全规则配置:掌握基于JSON规则的安全策略定义
动态权限验证:实现客户端和服务端的双重权限校验
实战案例:构建企业级文档管理系统权限模型
调试优化:掌握权限问题排查和性能优化技巧
AGC云存储的权限管理系统为HarmonyOS应用提供了:
企业级安全性:细粒度的访问控制
灵活配置:动态适应各种业务场景
无缝集成:与AGC认证服务的深度结合
开发效率:简化复杂权限逻辑的实现
在实际项目开发中,你还可以进一步探索:
结合AGC云函数实现更复杂的权限逻辑
使用自定义声明扩展用户权限属性
实现基于属性的访问控制(ABAC)模型
构建权限审计日志系统

浙公网安备 33010602011771号