Using Authorization Services with NSTask

半城伤御伤魂 提交于 2019-12-11 10:08:13

问题


Ok, I am using NSTask to run a shell script that needs to be run with administrator privileges. I am using some code from this question: NSTask and AuthorizationCreate. Here is what I currently have:

//Authorization Create
AuthorizationRef myAuthorizationRef;
OSStatus myStatus;
myStatus = AuthorizationCreate (NULL, kAuthorizationEmptyEnvironment,
                                kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed , &myAuthorizationRef);
AuthorizationItem myItems[1];

myItems[0].name = "com.myOrganization.myProduct.myRight1";
myItems[0].valueLength = 0;
myItems[0].value = NULL;
myItems[0].flags = 0;

AuthorizationRights myRights;
myRights.count = sizeof (myItems) / sizeof (myItems[0]);
myRights.items = myItems;

AuthorizationFlags myFlags;
myFlags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagExtendRights;

myStatus = AuthorizationCopyRights (myAuthorizationRef, &myRights,
                                    kAuthorizationEmptyEnvironment, myFlags, NULL);

if (myStatus==errAuthorizationSuccess)
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"kandorBackup" ofType:@"sh"];

    NSPipe *outputPipe = [NSPipe pipe];
    readHandle = [outputPipe fileHandleForReading];
    inData = nil;
    returnValue = nil;

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:path];
    [task setArguments:[NSArray arrayWithObjects:login, selectedDrive, rsyncFinalFlags, nil]];
    [task setStandardOutput:outputPipe];
    [readHandle waitForDataInBackgroundAndNotify];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(recievedData:)
                                                 name:NSFileHandleDataAvailableNotification

                                               object:nil];
    [task launch];
}
myStatus = AuthorizationFree (myAuthorizationRef,
                              kAuthorizationFlagDestroyRights);

When this executes, I am prompted for an administrator username and password, but then the task runs like it normally would, without elevated privileges. What am I missing to make NSTask actually use the authorization?


回答1:


Here you are just getting an AuthorizationRef and doing nothing with it, just getting the authorization doesn't make your executable run privileged. You can use the ref to launch an executable you embedded in your application using SMJobSubmit and within that executable, you can use NSTask with elevated permissions. Here is some example code explaining how this works: http://www.stairways.com/blog/2012-08-06-smjobsubmit



来源:https://stackoverflow.com/questions/25086160/using-authorization-services-with-nstask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!