Auto‑m365‑user‑add
Microsoft Graph API ile otomatik kullanıcı tedariki ve lisans atama script’i.
Özet
Bu araç, Azure AD uygulama kimlik bilgileri (Client Credentials flow) ile Microsoft Graph API’ye erişip yeni kullanıcı oluşturur ve lisans atar.
Gereksinimler
- Python 3.8+
- Azure AD’de uygulama (App registration) ve gerekli Graph izinleri
- Kitaplıklar:
msal,requests
pip install msal requests
Yapılandırma
Kimlik bilgilerini ortam değişkeni olarak ayarlayın:
$env:CLIENT_ID = "your_client_id" $env:CLIENT_SECRET = "your_client_secret" $env:TENANT_ID = "your_tenant_id"
Örnek kullanıcı ve lisans verisi script içinde yer alır; dilerseniz JSON’dan da okuyacak şekilde genişletilebilir.
Örnek Kod
import os
import msal
import requests
CLIENT_ID = os.getenv('CLIENT_ID')
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
TENANT_ID = os.getenv('TENANT_ID')
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"
SCOPE = ["https://graph.microsoft.com/.default"]
GRAPH = "https://graph.microsoft.com/v1.0"
app = msal.ConfidentialClientApplication(CLIENT_ID, authority=AUTHORITY, client_credential=CLIENT_SECRET)
def get_access_token():
result = app.acquire_token_for_client(scopes=SCOPE)
if 'access_token' in result:
return result['access_token']
raise RuntimeError('Token alınamadı: %s' % result)
def create_user(user_data):
token = get_access_token()
headers = { 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }
r = requests.post(f'{GRAPH}/users', headers=headers, json=user_data)
r.raise_for_status()
return r.json()
def assign_license(user_id, license_data):
token = get_access_token()
headers = { 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }
r = requests.post(f'{GRAPH}/users/{user_id}/assignLicense', headers=headers, json=license_data)
r.raise_for_status()
return r.json()
new_user = {
"accountEnabled": True,
"displayName": "ege uzun",
"mailNickname": "egeeee",
"userPrincipalName": "ege@yourdomain.com",
"passwordProfile": {
"forceChangePasswordNextSignIn": True,
"password": "your_password"
}
}
license_data = {
"addLicenses": [ { "skuId": "your_sku_id" } ],
"removeLicenses": []
}
created = create_user(new_user)
print(created)
assigned = assign_license(created['id'], license_data)
print(assigned)
Daha fazlası: Graph API — Kullanıcı oluştur
Güvenlik Notları
- İstemci sırrını (.env/KeyVault) güvenli saklayın; koda gömmeyin.
- Uygulama izinlerini en az ayrıcalık ilkesine göre verin.
- Üretimde hata/denge kontrolleri ve kayıt (logging) ekleyin.