对内容提供者强制执行项目所有权权限

Enforce item ownership permissions on content-provider

我有一个导出的内容提供程序,它在我的几个应用程序之间共享,一旦我发布了 API,第三方就可以免费为其编写他们自己的应用程序。

现在任何客户端应用程序都可以对内容提供程序中的任何项目执行任何 CRUD 操作。我想强制执行一些访问权限,以便应用程序只能修改或删除它创建的项目,同时仍允许任何应用程序读取提供程序中的所有项目并创建新项目。

有什么方法可以访问调用应用程序的 UID 并将其与新创建的项目一起存储,然后在未来的操作中与该值进行比较?使用包名会更好吗?我假设如果用户卸载并重新安装应用程序,UID 可能会更改,我不希望他们在这样做时失去对这些项目的访问权限。

是的,您可以检查包名。以下是根据调用 uid 检索包名称的方法:

private static Collection<String> getCallingPackages(Context context) {
    int callingUid = Binder.getCallingUid();
    if (callingUid == 0) {
        return Collections.emptyList();
    }

    String[] packages = context.getPackageManager().getPackagesForUid(callingUid);
    return new ArrayList<>(Arrays.asList(packages));
}

这个 returns 包名称列表,因为引用文档:

In most cases, this will be a single package name, the package that has been assigned that user id.

Where there are multiple packages sharing the same user id through the "sharedUserId" mechanism, all packages with that id will be returned.