授权在Cocoa应用程序中以管理员身份写入文件

时间:2013-07-16 19:46:11

标签: cocoa authorization

在我的Cocoa应用程序中,我需要写一个plist到一个特权位置,所以我正在研究安全框架。我有下面的代码,它似乎正确弹出对话框要求管理员密码,我确实看到自己点击'成功'块。但是,我在这里错过了两件作品:

  1. 如何以原子方式执行writeToUrl:使用那些提升的权限?
  2. 如何将权限恢复到用户最初的权限?
  3. 这是我正在使用的方法:

    - (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);
        }
    }
    

0 个答案:

没有答案