频道栏目
首页 > 资讯 > Python > 正文

python3登录azureAD并调用azuregraphapi

17-08-29        来源:[db:作者]  
收藏   我要投稿

python3登录azureAD并调用azuregraphapi

parameters.json :

 {
   "resource": "https://graph.microsoft.com/",
   "tenant" : "{your_directoryId}",
   "authorityHostUrl" : "https://login.microsoftonline.com",
   "clientid" : "{your_app_id}",
   "username" : "{username}",
   "password" : "{password}"
 }

test.py:

import json
import logging
import os
import sys
import adal


parameters_file = (sys.argv[1] if len(sys.argv) == 2 else
                   os.environ.get('ADAL_SAMPLE_PARAMETERS_FILE'))

if parameters_file:
    with open(parameters_file, 'r') as f:
        parameters = f.read()
    sample_parameters = json.loads(parameters)
else:
    raise ValueError('Please provide parameter file with account information.')

authority_url = (sample_parameters['authorityHostUrl'] + '/' +
                 sample_parameters['tenant'])
GRAPH_RESOURCE = '00000002-0000-0000-c000-000000000000'
RESOURCE = sample_parameters.get('resource', GRAPH_RESOURCE)

#uncomment for verbose log
#turn_on_logging()

context = adal.AuthenticationContext(
    authority_url, validate_authority=sample_parameters['tenant'] != 'adfs',
    api_version=None)

########################################################
# below is the token based on username/password
########################################################
tokenRet = context.acquire_token_with_username_password(
    RESOURCE,
    sample_parameters['username'],
    sample_parameters['password'],
    sample_parameters['clientid'])
token = tokenRet['accessToken']
print('Here is the access token get by username/password')
print(json.dumps(token, indent=2))




########################################################
# below code to get access token based on refresh token
#########################################################
refresh_token = tokenRet['refreshToken']
retToken = context.acquire_token_with_refresh_token(
    refresh_token,
    sample_parameters['clientid'],
    RESOURCE)
token = retToken['accessToken']
print('Here is the token acquired from the refreshing token')
print(json.dumps(token, indent=2))


###########################################################
# below is the user profile information get from azure graph api
#  for more information:
# https://developer.microsoft.com/en-us/graph/graph-explorer
############################################################
import urllib2
req = urllib2.Request('https://graph.microsoft.com/v1.0/users')
req.add_header('Authorization', 'Bearer '+token)
resp = urllib2.urlopen(req)
content = resp.read()
print('below is the user profile info:')
print(content)



相关TAG标签
上一篇:# leetcode 110. balanced Binary Tree
下一篇:Go语言-接口
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站