// testright.c
#include <stdio.h>
#include <stdlib.h>
#include <CoreFoundation/CoreFoundation.h>
#include <Security/Authorization.h>
#include <Security/AuthorizationDB.h>
const char kTestActionRightName[] = "com.osxbook.Test.DoSomething";
int
main(int argc, char **argv)
{
OSStatus err;
AuthorizationRef authRef;
AuthorizationItem authorization = { 0, 0, 0, 0 };
AuthorizationRights rights = { 1, &authorization };
AuthorizationFlags flags = kAuthorizationFlagInteractionAllowed |kAuthorizationFlagExtendRights;
// Create a new authorization reference
err = AuthorizationCreate(NULL, NULL, 0, &authRef);
if (err != noErr) {
fprintf(stderr, "failed to connect to Authorization Services\n");
return err;
}
// Check if the right is defined
err = AuthorizationRightGet(kTestActionRightName, NULL);
if (err != noErr) {
if (err == errAuthorizationDenied) {
// Create right in the policy database
err = AuthorizationRightSet(
authRef,
kTestActionRightName,
CFSTR(kAuthorizationRuleAuthenticateAsSessionUser),
CFSTR("You must be authorized to perform DoSomething."),
NULL,
NULL
);
if (err != noErr) {
fprintf(stderr, "failed to set up right\n");
return err;
}
}
else {
// Give up
fprintf(stderr, "failed to check right definition (%ld)\n", err);
return err;
}
}
// Authorize right
= kTestActionRightName;
err = AuthorizationCopyRights(authRef, &rights, NULL, flags, NULL);
if (err != noErr)
fprintf(stderr, "failed to acquire right (%s)\n", kTestActionRightName);
else
fprintf(stderr, "right acquired (%s)\n", kTestActionRightName);
// Free the memory associated with the authorization reference
AuthorizationFree(authRef, kAuthorizationFlagDefaults);
exit(0);
}
haidragondeMacBook-Air:2-35 haidragon$ gcc -Wall -o testright testright.c -framework Security -framework CoreFoundation
testright.c:46:73: warning: values of type 'OSStatus' should not be used as format arguments; add an
explicit cast to 'int' instead [-Wformat]
fprintf(stderr, "failed to check right definition (%ld)\n", err);
~~~ ^~~
%d (int)
1 warning generated.
haidragondeMacBook-Air:2-35 haidragon$ ls
testright testright.c
haidragondeMacBook-Air:2-35 haidragon$ ./testright
right acquired (com.osxbook.Test.DoSomething)
haidragondeMacBook-Air:2-35 haidragon$ ./testright
failed to acquire right (com.osxbook.Test.DoSomething)
haidragondeMacBook-Air:2-35 haidragon$
https://www.exchen.net/objective-c-macos%e4%bb%a5%e7%ae%a1%e7%90%86%e5%91%98%e6%9d%83%e9%99%90%e8%bf%90%e8%a1%8c%e7%a8%8b%e5%ba%8f.html