iOS客户端:我可以让用户登录Active Directory,但是如何访问MS Graph API?

我正在开发一个需要从MS Azure Active Directory读取用户数据的iOS应用程序.

我已成功地从MS Azure文档中了解了iOS应用程序上的一些示例,并成功启动了其身份验证页面并让用户登录.我得到的是ADUserInformation对象形式的一些用户数据.

这是我的代码:

    NSString *authority = @"https://login.microsoftonline.com/a5960f61-0bf9-4bf6-96cd-98c61d30XXXX/federationmetadata/2007-06/federationmetadata.xml";

    NSString *resourceId    = @"74cd2559-0389-4871-9904-bc767d71XXXX"; // (server)

    NSString *clientId      = @"c8a956a7-84b7-4050-875c-896aab6bXXXX";   //ios-client (us)

    NSURL *redirectUri = [[NSURL alloc]initWithString:@"https://XXXXevents.azurewebsites.net/.auth/login/done"];

    ADAuthenticationError *error;

    ADAuthenticationContext * authContext = [ADAuthenticationContext authenticationContextWithAuthority:authority error:&error];

    //authContext.parentController = parent;

    [ADAuthenticationSettings sharedInstance].enableFullScreen = YES;

    [authContext acquireTokenWithResource:resourceId
                                 clientId:clientId
                              redirectUri:redirectUri
                          completionBlock:^(ADAuthenticationResult *result) {

          if (result.status != AD_SUCCEEDED) {
              NSLog(@"%@", result);
              return;
          }
          else {

              //save all of this information into core data

              NSDictionary * payload = @{@"access_token" : result.tokenCacheItem.accessToken};
              NSLog(@"%@", payload);

              //@"aad"
              //@"windowsazureactivedirectory"

              [[QSActivityService defaultService].client loginWithProvider:     @"aad"
                                                                     token:     payload
                                                                completion:     ^(MSUser * _Nullable user, NSError * _Nullable error) {

                                                                NSLog(@"loginWithProvider-------");
                  if(!error) {
                      NSLog(@"YAY! %s - user: %@ ", __FUNCTION__, user.userId);

                      ADUserInformation * temp = result.tokenCacheItem.userInformation;

                                           [[CoreDataStack defaultStack] updateUserDetailFamilyName:temp.allClaims[@"family_name"]
                                                                           version:temp.allClaims[@"ver"]
                                                                             email:temp.allClaims[@"email"]
                                                                               nbf:temp.allClaims[@"nbf"]
                                                                               exp:temp.allClaims[@"exp"]
                                                                         givenName:temp.allClaims[@"given_name"]
                                                                               idp:temp.allClaims[@"idp"]
                                                                            ipaddr:temp.allClaims[@"ipaddr"]
                                                                               iss:temp.allClaims[@"iss"]
                                                                               oid:temp.allClaims[@"oid"]
                                                                               typ:temp.allClaims[@"typ"]
                                                                               sub:temp.allClaims[@"sub"]
                                                                               amr:temp.allClaims[@"amr"]
                                                                               aud:temp.allClaims[@"aud"]
                                                                               alg:temp.allClaims[@"alg"]
                                                                               iat:temp.allClaims[@"iat"]
                                                                               tid:temp.allClaims[@"tid"]
                                                                              name:temp.allClaims[@"name"]
                                                                        uniqueName:temp.allClaims[@"unique_name"]];

    //other code, no problems here

MS Graph API

但是,我想访问配置文件图像和所有其他数据.我已经读过MS Graph API提供它,但我不确定如何以及在何处放置令牌.

我是否使用result.tokenCacheItem.accessToken中的令牌?如果是这样,在标题中?还是身体?

或者我只是简单地点击graph.windows.com两次.第一次获得身份验证令牌,第二次获取数据?

我已经阅读了很多文档,但没有一个工作,因为我不断收到令牌丢失或格式错误的错误消息.

My Graph API代码如下所示:

-(void)getUsersUsingAccessToken:(NSDictionary*)token completion:(void (^)    (void))completion {

    NSString * tenant = @"a5960f61-0bf9-4bf6-96cd-98c61d306f12";

    NSString * accessToken = token[@"access_token"];

    NSString * urlString = [NSString stringWithFormat: @"https://graph.windows.net/%@/tenantDetails?api-version=1.6", tenant];

    NSString * httpVerb = @"POST";

    //build an info object and convert to json
    NSDictionary * bodyFormDict

    = [NSDictionary dictionaryWithObjectsAndKeys:
     @"client_credentials",                              @"grant_type",
     @"https://graph.windows.net",                       @"resource",
     @"c8a956a7-84b7-4050-875c-896aab6xxxx",            @"client_id",
     @"XLlZl69aUKiQTo4dpeiprItm+LYbDtpt6e9dn0bxxxx",    @"client_secret",
     nil];

    NSError *error = nil;

    //1st step
    NSData * jsonInputData = [NSJSONSerialization dataWithJSONObject:bodyFormDict
                                                             options:NSJSONWritingPrettyPrinted
                                                               error:&error];

    //2nd step
    NSString * httpBodyString = [[NSString alloc]
                                 initWithData:jsonInputData
                                 encoding:NSUTF8StringEncoding];


    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfiguration.allowsCellularAccess = YES;

    self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration];

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = httpVerb;

    [request setValue:  @"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:  accessToken forHTTPHeaderField:@"Authorization: Bearer"];

    [request setHTTPBody:[httpBodyString dataUsingEncoding:NSUTF8StringEncoding]];

    //asynchronous
    NSURLSessionDataTask * getDataTask = [self.session dataTaskWithRequest:request
                                                         completionHandler:^(NSData * _Nullable data,
                                                                             NSURLResponse * _Nullable response,
                                                                             NSError * _Nullable error) {

    //other code

}

如果有人可以使用目标c提供工作代码示例以成功从MS Graph API检索数据,那将是一个很大的帮助.

谢谢你的时间!

最佳答案 我相信你遇到的问题是http头字段设置不正确.试试这个 –

    NSString *authValue = [NSString stringWithFormat:@"Bearer %@", accessToken];
    [request setValue:authValue forHTTPHeaderField:@"Authorization"];
点赞