4

在我的 Cocoa 应用程序中,我需要将 plist 写入特权位置,因此我正在研究安全框架。我有下面的代码,它似乎确实正确地弹出了询问管理员密码的对话框,我确实看到自己点击了“成功”块。但是,我在这里缺少两件:

  1. 如何使用那些提升的权限执行 writeToUrl:atomically:?
  2. 如何将 privs 恢复为用户最初拥有的权限?

这是我正在使用的方法:

- (void)writePreferences:(NSDictionary *)prefs url:(NSURL *)url {
    AuthorizationRef auth = NULL;
    OSStatus authResult = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &auth);
    if (errAuthorizationSuccess != authResult) {
        NSLog(@"couldn't create authorization object, error %d", authResult);
        exit(-1);
    }

    @try {
        AuthorizationItem item;
        item.name = "com.gargoylesoft.FolderWatch.writePrefs";
        item.valueLength = 0;
        item.value = NULL;
        item.flags = 0;

        AuthorizationRights requestedRights;
        requestedRights.count = 1;
        requestedRights.items = &item;

        AuthorizationRights *grantedRights = NULL;
        authResult = AuthorizationCopyRights(auth,
                                             &requestedRights,
                                             kAuthorizationEmptyEnvironment,
                                             kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed,
                                             &grantedRights);

        if (authResult == errAuthorizationSuccess) {
            [prefs writeToURL:url atomically:YES];
        }

        AuthorizationFreeItemSet(grantedRights);
    } @finally {
        AuthorizationFree(auth, kAuthorizationFlagDefaults);
    }
}
4

0 回答 0