iOS/OS X-kodexempel

Viktigt

Versioner av Microsoft Rights Management Service SDK som släpptes före mars 2020 är inaktuella. program som använder tidigare versioner måste uppdateras för att använda mars 2020-versionen. Fullständig information finns i utfasningsmeddelandet.

Inga ytterligare förbättringar planeras för Microsoft Rights Management Service SDK. Vi rekommenderar starkt att du använder Microsoft Information Protection SDK för klassificerings-, märknings- och skyddstjänster.

I det här avsnittet beskrivs viktiga kodelement för iOS/OS X-versionen av RMS SDK.

Observera I exempelkoden och beskrivningarna som följer använder vi termen MSIPC (Microsoft Information Protection och Kontroll) för att referera till klientprocessen.

Använda Microsoft Rights Management SDK 4.2 – nyckelscenarier

Följande är Objective C-kodexempel från ett större exempelprogram som representerar utvecklingsscenarier som är viktiga för din förståelse av detta SDK. Dessa demonstrerar användningen av formatet Microsoft-skyddad fil, här kallat skyddad fil, användningen av anpassade skyddade filformat och användningen av anpassade UI-kontroller.

Scenario: Använda en RMS-skyddad fil

  • Steg 1: Skapa ett MSProtectedData-objekt

    Beskrivning: Skapa en instans av ett MSProtectedData-objekt som implementerar tjänstautentisering med hjälp av MSAuthenticationCallback för att hämta en token genom att skicka en instans av MSAuthenticationCallback, som parametern authenticationCallback, till MSIPC-API:et. Se anropet till MSProtectedData protectedDataWithProtectedFile i följande avsnitt med exempelkod.

        + (void)consumePtxtFile:(NSString *)path authenticationCallback:(id<MSAuthenticationCallback>)authenticationCallback
        {
            // userId can be provided as a hint for authentication
            [MSProtectedData protectedDataWithProtectedFile:path
                                                 userId:nil
                                 authenticationCallback:authenticationCallback
                                                options:Default
                                        completionBlock:^(MSProtectedData *data, NSError *error)
            {
                //Read the content from the ProtectedData, this will decrypt the data
                NSData *content = [data retrieveData];
            }];
        }
    
  • Steg 2: Konfigurera autentisering med hjälp av ADAL (Active Directory Authentication Library).

    Beskrivning: I det här steget ser du hur ADAL används för att implementera ett MSAuthenticationCallback med exempelautentiseringsparametrar. Mer information om hur du använder ADAL finns i Azure AD Authentication Library (ADAL).

      // AuthenticationCallback holds the necessary information to retrieve an access token.
      @interface MsipcAuthenticationCallback : NSObject<MSAuthenticationCallback>
    
      @end
    
      @implementation MsipcAuthenticationCallback
    
      - (void)accessTokenWithAuthenticationParameters:
             (MSAuthenticationParameters *)authenticationParameters
                                    completionBlock:
             (void(^)(NSString *accessToken, NSError *error))completionBlock
      {
          ADAuthenticationError *error;
          ADAuthenticationContext* context = [
              ADAuthenticationContext authenticationContextWithAuthority:authenticationParameters.authority
                                                                error:&error
          ];
          NSString *appClientId = @"com.microsoft.sampleapp";
          NSURL *redirectURI = [NSURL URLWithString:@"local://authorize"];
          // Retrieve token using ADAL
          [context acquireTokenWithResource:authenticationParameters.resource
                                 clientId:appClientId
                              redirectUri:redirectURI
                                   userId:authenticationParameters.userId
                          completionBlock:^(ADAuthenticationResult *result) {
                              if (result.status != AD_SUCCEEDED)
                              {
                                  NSLog(@"Auth Failed");
                                  completionBlock(nil, result.error);
                              }
                              else
                              {
                                  completionBlock(result.accessToken, result.error);
                              }
                          }];
       }
    
  • Steg tre: Kontrollera om användaren har redigeringsbehörighet till detta innehåll via metoden MSUserPolicy accessCheck för ett MSUserPolicy-objekt.

      - (void)accessCheckWithProtectedData:(MSProtectedData *)protectedData
      {
          //check if user has edit rights and apply enforcements
          if (!protectedData.userPolicy.accessCheck(EditableDocumentRights.Edit))
          {
              // enforce on the UI
              textEditor.focusableInTouchMode = NO;
              textEditor.focusable = NO;
              textEditor.enabled = NO;
          }
      }
    

Scenario: Skapa en ny skyddad fil med en mall

I det här scenariot börjar vi med att hämta en lista över mallar, MSTemplateDescriptor Vi väljer den första mallen för att skapa en princip och skapar och skriver sedan till den nya skyddade filen.

  • Steg 1: Hämta lista över mallar

        + (void)templateListUsageWithAuthenticationCallback:(id<MSAuthenticationCallback>)authenticationCallback
        {
            [MSTemplateDescriptor templateListWithUserId:@"user@domain.com"
                            authenticationCallback:authenticationCallback
                                   completionBlock:^(NSArray/*MSTemplateDescriptor*/ *templates, NSError *error)
                                   {
                                     // use templates array of MSTemplateDescriptor (Note: will be nil on error)
                                   }];
        }
    
  • Steg två: Skapa en MSUserPolicy med hjälp av den första mallen i listan.

        + (void)userPolicyCreationFromTemplateWithAuthenticationCallback:(id<MSAuthenticationCallback>)authenticationCallback
        {
            [MSUserPolicy userPolicyWithTemplateDescriptor:[templates objectAtIndex:0]
                                            userId:@"user@domain.com"
                                     signedAppData:nil
                            authenticationCallback:authenticationCallback
                                           options:None
                                   completionBlock:^(MSUserPolicy *userPolicy, NSError *error)
            {
            // use userPolicy (Note: will be nil on error)
            }];
        }
    
  • Steg tre: Skapa ett MSMutableProtectedData-objekt och skriv innehåll till det.

        + (void)createPtxtWithUserPolicy:(MSUserPolicy *)userPolicy contentToProtect:(NSData *)contentToProtect
        {
            // create an MSMutableProtectedData to write content
            [contentToProtect protectedDataInFile:filePath
                        originalFileExtension:kDefaultTextFileExtension
                               withUserPolicy:userPolicy
                              completionBlock:^(MSMutableProtectedData *data, NSError *error)
            {
             // use data (Note: will be nil on error)
            }];
        }
    

Scenario: Öppna en anpassad skyddad fil

  • Steg ett: Skapa en MSUserPolicyfrån en serializedContentPolicy.

        + (void)userPolicyWith:(NSData *)protectedData
        authenticationCallback:(id<MSAuthenticationCallback>)authenticationCallback
        {
            // Read header information from protectedData and extract the  PL
            /*-------------------------------------------
            | PL length | PL | ContetSizeLength |
            -------------------------------------------*/
            NSUInteger serializedPolicySize;
            NSMutableData *serializedPolicy;
            [protectedData getBytes:&serializedPolicySize length:sizeof(serializedPolicySize)];
            [protectedData getBytes:[serializedPolicy mutableBytes] length:serializedPolicySize];
    
            // Get the user policy , this is an async method as it hits the REST service
            // for content key and usage restrictions
            // userId provided as a hint for authentication
            [MSUserPolicy userPolicyWithSerializedPolicy:serializedPolicy
                                              userId:@"user@domain.com"
                              authenticationCallback:authenticationCallback
                                             options:Default
                                     completionBlock:^(MSUserPolicy *userPolicy,
                                                       NSError *error)
            {
    
            }];
         }
    
  • Steg två: Skapa ett MSCustomProtectedData-objekt med hjälp av MSUserPolicy från Steg ett och läs från det.

        + (void)customProtectedDataWith:(NSData *)protectedData
        {
            // Read header information from protectedData and extract the  protectedContentSize
            /*-------------------------------------------
            | PL length | PL | ContetSizeLength |
            -------------------------------------------*/
            NSUInteger protectedContentSize;
            [protectedData getBytes:&protectedContentSize
                         length:sizeof(protectedContentSize)];
    
            // Create the MSCustomProtector used for decrypting the content
            // The content start position is the header length
            [MSCustomProtectedData customProtectedDataWithPolicy:userPolicy
                                               protectedData:protectedData
                                        contentStartPosition:sizeof(NSUInteger) + serializedPolicySize
                                                 contentSize:protectedContentSize
                                             completionBlock:^(MSCustomProtectedData *customProtector,
                                                               NSError *error)
            {
             //Read the content from the custom protector, this will decrypt the data
             NSData *content = [customProtector retrieveData];
             NSLog(@"%@", content);
            }];
         }
    

Scenario: Skapa en anpassad skyddad fil med hjälp av en anpassad princip (ad hoc)

  • Steg 1: Skapa en principbeskrivning med en e-postadress som anges av användaren.

    Beskrivning: I praktiken skapas följande objekt med användarindata från enhetsgränssnittet: MSUserRights och MSPolicyDescriptor.

        + (void)policyDescriptor
        {
            MSUserRights *userRights = [[MSUserRights alloc] initWithUsers:[NSArray arrayWithObjects: @"user1@domain.com", @"user2@domain.com", nil] rights:[MSEmailRights all]];
    
            MSPolicyDescriptor *policyDescriptor = [[MSPolicyDescriptor alloc] initWithUserRights:[NSArray arrayWithObjects:userRights, nil]];
            policyDescriptor.contentValidUntil = [[NSDate alloc] initWithTimeIntervalSinceNow:NSTimeIntervalSince1970 + 3600.0];
            policyDescriptor.offlineCacheLifetimeInDays = 10;
        }
    
  • Steg 2: Skapa en anpassad MSUserPolicy från principbeskrivningen, selectedDescriptor.

        + (void)userPolicyWithPolicyDescriptor:(MSPolicyDescriptor *)policyDescriptor
        {
            [MSUserPolicy userPolicyWithPolicyDescriptor:policyDescriptor
                                          userId:@"user@domain.com"
                          authenticationCallback:authenticationCallback
                                         options:None
                                 completionBlock:^(MSUserPolicy *userPolicy, NSError *error)
            {
              // use userPolicy (Note: will be nil on error)
            }];
        }
    
  • Steg 3: Skapa och skriv innehåll till MSMutableCustomProtectedData och stäng sedan.

        + (void)mutableCustomProtectedData:(NSMutableData *)backingData policy:(MSUserPolicy *)policy contentToProtect:(NSString *)contentToProtect
        {
            //Get the serializedPolicy from a given policy
            NSData *serializedPolicy = [policy serializedPolicy];
    
            // Write header information to backing data including the PL
            // ------------------------------------
            // | PL length | PL | ContetSizeLength |
            // -------------------------------------
            NSUInteger serializedPolicyLength = [serializedPolicy length];
            [backingData appendData:[NSData dataWithBytes:&serializedPolicyLength length:sizeof(serializedPolicyLength)]];
            [backingData appendData:serializedPolicy];
            NSUInteger protectedContentLength = [MSCustomProtectedData getEncryptedContentLengthWithPolicy:policy contentLength:unprotectedData.length];
            [backingData appendData:[NSData dataWithBytes:&protectedContentLength length:sizeof(protectedContentLength)]];
    
            NSUInteger headerLength = sizeof(serializedPolicyLength) + serializedPolicyLength + sizeof(protectedContentLength);
    
            // Create the MSMutableCustomProtector used for encrypting content
            // The content start position is the current length of the backing data
            // The encryptedContentSize content size is 0 since there is no content yet
            [MSMutableCustomProtectedData customProtectorWithUserPolicy:policy
                                                        backingData:backingData
                                             protectedContentOffset:headerLength
                                                    completionBlock:^(MSMutableCustomProtectedData *customProtector,
                                                                      NSError *error)
            {
                //Append data to the custom protector, this will encrypt the data and write it to the backing data
                [customProtector appendData:[contentToProtect dataUsingEncoding:NSUTF8StringEncoding] error:&error];
    
                //close the custom protector so it will flush and finalise encryption
                [customProtector close:&error];
    
            }];
          }