gpt4 book ai didi

iOS 验证 Azure Active Directory 并从 office 365 exchange 获取日历事件

转载 作者:行者123 更新时间:2023-11-29 02:28:10 24 4
gpt4 key购买 nike

尝试使用 Azure Active Directory 进行身份验证并获取邮件、日历数据,成功返回 accessToken:

authority = @"https://login.windows.net/common/oauth2/authorize";
redirectUriString = @"http://xxxxxx.xxxxxxx.com/oauth";
resourceId = @"https://outlook.office365.com";
clientId = @"xxxxxxx-xxxxx-xxx";

-(void) getToken : (BOOL) clearCache completionHandler:(void (^) (NSString*))completionBlock;
{
ADAuthenticationError *error;
authContext = [ADAuthenticationContext authenticationContextWithAuthority:authority
error:&error];
[authContext setValidateAuthority:YES];

NSURL *redirectUri = [NSURL URLWithString:redirectUriString];

if(clearCache){
[authContext.tokenCacheStore removeAllWithError:&error];

if (error) {
NSLog(@"Error: %@", error);
}
}


[authContext acquireTokenWithResource:resourceId
clientId:clientId
redirectUri:redirectUri
completionBlock:^(ADAuthenticationResult *result) {
if (AD_SUCCEEDED != result.status){
// display error on the screen
[self showError:result.error.errorDetails];
}
else{
completionBlock(result.accessToken);
}
}];

-(NSArray*)getEventsList{

__block NSMutableArray * todoList;

[self getToken:YES completionHandler:^(NSString* accessToken){

NSURL *todoRestApiURL = [[NSURL alloc]initWithString:@"https://outlook.office365.com/api/v1.0/me/folders/inbox/messages?$top=2"];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:todoRestApiURL];

NSString *authHeader = [NSString stringWithFormat:@"Bearer %@", @""];

[request addValue:authHeader forHTTPHeaderField:@"Authorization"];

[request addValue:@"application/json; odata.metadata=none" forHTTPHeaderField:@"accept"];


[request addValue:@"fbbadfe-9211-1234-9654-fe435986a1d6" forHTTPHeaderField:@"client-request-id"];

[request addValue:@"Presence-Propelics/1.0" forHTTPHeaderField:@"User-Agent"];
//[request addValue:@"true" forHTTPHeaderField:@"return-client-request-id"];



NSOperationQueue *queue = [[NSOperationQueue alloc]init];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

if (error == nil){

NSArray *scenarios = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

todoList = [[NSMutableArray alloc]initWithArray:scenarios];

//each object is a key value pair
NSDictionary *keyVauePairs;

for(int i =0; i < todoList.count; i++)
{
keyVauePairs = [todoList objectAtIndex:i];

NSLog(@"%@", keyVauePairs);

}

}
NSLog(@"Finished");
//[delegate updateTodoList:TodoList];

}];

}];
return nil; }

响应对象返回错误:

{ 错误 = { 代码 = ErrorAccessDenied; message = "访问被拒绝。请检查凭据并重试。"; };

最佳答案

我知道回答这个问题已经晚了,但它可能对像我这样正在努力完成同样事情的人有所帮助

我已经使用 office 365 SDK 完成了此操作适用于 iOS,它具有所有内置类来完成您的工作。

如果您下载他们的示例代码,它将为您提供执行某些操作(邮件、日历、联系人、一个驱动器)所需的所有详细信息。

在使用 SDK 之前,请确保您登录到 Azure AD 和 register your application and add permissions这样您就不会收到 403 错误代码或任何访问被拒绝的消息。

我正在使用下面的代码从 Outlook 日历中获取我的事件详细信息

    [self getClientEvents:^(MSOutlookClient *client) {
NSURLSessionDataTask *task = [[[client getMe] getEvents] read:^(NSArray<MSOutlookEvent> *events, MSODataException *error) {

if (error==nil) {
if (events.count!=0) {

dispatch_async(dispatch_get_main_queue(), ^{
for(MSOutlookEvent *calendarEvent in events){
NSLog(@"name = %@",calendarEvent.Subject);
}
});
}else{
NSLog(@"No events found for today");
}
}
}];
[task resume];
}];

getClientEvents 是一种调用 Office 365 SDK 并获取用户的事件详细信息的方法,但它首先获取资源的 token ,然后使用获取的 token 进行调用

-(void)getClientEvents : (void (^) (MSOutlookClient* ))callback{

[self getTokenWith : @"https://outlook.office365.com" :true completionHandler:^(NSString *token) {

MSODataDefaultDependencyResolver* resolver = [MSODataDefaultDependencyResolver alloc];
MSODataOAuthCredentials* credentials = [MSODataOAuthCredentials alloc];
[credentials addToken:token];

MSODataCredentialsImpl* credentialsImpl = [MSODataCredentialsImpl alloc];

[credentialsImpl setCredentials:credentials];
[resolver setCredentialsFactory:credentialsImpl];
[[resolver getLogger] log:@"Going to call client API" :(MSODataLogLevel *)INFO];

callback([[MSOutlookClient alloc] initWithUrl:@"https://outlook.office365.com/api/v1.0" dependencyResolver:resolver]);
}];
}

getTokenWith 方法 首先获取资源的 token ,然后使用获取的 token 进行必要的调用以获取事件,但在获取 token 之前,它会在缓存中检查是否有任何事件可用于同一资源的 token 。

// fetch tokens for resources
- (void) getTokenWith :(NSString *)resourceId : (BOOL) clearCache completionHandler:(void (^) (NSString *))completionBlock;
{
// first check if the token for the resource is present or not
if([self getCacheToken : resourceId completionHandler:completionBlock]) return;

ADAuthenticationError *error;
authContext = [ADAuthenticationContext authenticationContextWithAuthority:[[NSUserDefaults standardUserDefaults] objectForKey:@"authority"] error:&error];

NSURL *redirectUri = [NSURL URLWithString:@"YOUR_REDIRECT_URI"];

[authContext acquireTokenWithResource:resourceId
clientId:[[NSUserDefaults standardUserDefaults] objectForKey:@"clientID"]
redirectUri:redirectUri
completionBlock:^(ADAuthenticationResult *result) {

if (AD_SUCCEEDED != result.status){
[self showError:result.error.errorDetails];
}
else{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:result.tokenCacheStoreItem.userInformation.userId forKey:@"LogInUser"];
[userDefaults synchronize];

completionBlock(result.accessToken);
}
}];
}

getCacheToken 方法:检查是否有任何资源的可重用 token 。

-(BOOL)getCacheToken : (NSString *)resourceId  completionHandler:(void (^) (NSString *))completionBlock {
ADAuthenticationError * error;
id<ADTokenCacheStoring> cache = [ADAuthenticationSettings sharedInstance].defaultTokenCacheStore;
NSArray *array = [cache allItemsWithError:&error];

if([array count] == 0) return false;
ADTokenCacheStoreItem *cacheItem;

for (ADTokenCacheStoreItem *item in array) {
if([item.resource isEqualToString:resourceId]){
cacheItem = item;
break;
}
}

ADUserInformation *user = cacheItem.userInformation;

if(user == nil) return false;

if([cacheItem isExpired]){
return [self refreshToken:resourceId completionHandler:completionBlock];
}
else
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:user.userId forKey:@"LogInUser"];
[userDefaults synchronize];

completionBlock(cacheItem.accessToken);

return true;
}
}

使用此代码和 Office 365 SDK,您可以获取特定用户的 Outlook 事件,在此之前,请确保您在 Azure AD 中拥有完全权限,否则您可能会收到 0 个事件作为响应。

请注意,除了第一个查看如何获取事件的方法之外,所有方法均来自 SDK 示例,我建议下载 exchange example from the github .

关于iOS 验证 Azure Active Directory 并从 office 365 exchange 获取日历事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27232995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com