인디노트

AuthorizationExecuteWithPrivileges 대신 SMJobBless 본문

소스 팁/Objective C, Swift, iOS, macOS

AuthorizationExecuteWithPrivileges 대신 SMJobBless

인디개발자 2023. 3. 29. 14:48

MacOS 10.7 (Lion)부터 Apple은 AuthorizationExecuteWithPrivileges 함수를 더 이상 권장하지 않으며, 대신 SMJobBless 함수를 사용하도록 권장합니다. SMJobBless 함수는 권한이 필요한 작업을 수행하기 위해 Launch Services를 사용하여 승인된 helper 도구를 설치하고 실행하는 기능을 제공합니다.

아래는 SMJobBless 함수를 사용하여 승인된 helper 도구를 설치하고 실행하는 예시 코드입니다:

// import 필요
#import <ServiceManagement/ServiceManagement.h>

// ...

// helper 도구의 Bundle ID
NSString *helperBundleID = @"com.example.helper";

// helper 도구를 설치하기 위한 인증 객체 생성
NSError *error = nil;
AuthorizationItem authItem = { kSMRightBlessPrivilegedHelper, 0, NULL, 0 };
AuthorizationRights authRights = { 1, &authItem };
AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights;
AuthorizationRef authRef = NULL;
OSStatus status = AuthorizationCreate(&authRights, kAuthorizationEmptyEnvironment, flags, &authRef);

// helper 도구를 설치하고 실행
if (status == errAuthorizationSuccess) {
    CFErrorRef blessError = NULL;
    if (SMJobBless(kSMDomainSystemLaunchd, (__bridge CFStringRef)helperBundleID, authRef, &blessError)) {
        // helper 도구 설치 성공, 실행
        status = system("launchctl start com.example.helper");
        if (status != 0) {
            NSLog(@"Error: Failed to start helper tool (status=%d)", status);
        }
    } else {
        // helper 도구 설치 실패
        error = (__bridge NSError *)blessError;
        NSLog(@"Error: Failed to bless helper tool (%@)", error.localizedDescription);
    }
}

// ...

// 인증 객체 해제
AuthorizationFree(authRef, kAuthorizationFlagDefaults);

위 코드에서는 SMJobBless 함수를 사용하여 helper 도구를 설치하고 실행합니다. SMJobBless 함수를 호출하기 전에 인증 객체를 생성해야 합니다. SMJobBless 함수가 실패하면 NSError를 반환합니다.

위 코드에서는 system 함수를 사용하여 helper 도구를 실행합니다. 이 함수는 주어진 명령을 실행하고 명령의 반환값을 반환합니다. 여기서는 launchctl 명령을 사용하여 helper 도구를 실행합니다.

위 코드에서는 helper 도구의 Bundle ID를 com.example.helper로 가정하고 있습니다. 이 값을 실제 helper 도구의 Bundle ID로 바꾸어 사용해야 합니다.

반응형
Comments