הגדרת Groups API
בדף הזה מוסבר איך להגדיר את Cloud Identity Groups API.
לפני שמתחילים
מפעילים את Cloud Identity API.
תפקידים שנדרשים להפעלת ממשקי API
כדי להפעיל ממשקי API, צריך את תפקיד ה-IAM 'אדמין של Service Usage' (roles/serviceusage.serviceUsageAdmin), שכולל את ההרשאה serviceusage.services.enable. איך מקצים תפקידים
התקנת ספריות הלקוח
כדי להתקין את ספריות הלקוח, מריצים את הפקודה הבאה:
Python
מידע נוסף על הגדרת סביבת הפיתוח בשפת Python מופיע במדריך להגדרת סביבת הפיתוח בשפת Python.
pip install --upgrade google-api-python-client google-auth \
google-auth-oauthlib google-auth-httplib2
אימות באמצעות Groups API
אפשר לבצע אימות באמצעות Groups API כמשתמש קצה, כאדמין של קבוצת חשבון שירות ללא הקצאת הרשאות ברמת הדומיין, או כחשבון שירות עם הקצאת הרשאות ברמת הדומיין. בקטעים הבאים מתוארת כל שיטה.
ביצוע אימות כמשתמשי קצה
אם אתם לא אדמינים, או אם אתם מפתחים אפליקציה שפועלת בשם משתמשים שהם לא אדמינים, כדאי לעיין במאמר שימוש ב-OAuth 2.0 לאפליקציות שרת אינטרנט ואז לעבור לקטע יצירת מופע של לקוח שבהמשך.
אימות כחשבון שירות בלי הקצאה ברמת הדומיין
אם אתם משתמשים בחשבון שירות ואתם רוצים להשתמש בו כדי לנהל קבוצות כאדמינים של קבוצות, אתם צריכים לבצע את השלבים הבאים. צריך להשתמש בשיטת האימות הזו כשרוצים שהפעולות של חשבון השירות יירשמו ביומני הביקורת כחשבון השירות.
הקצאת תפקיד אדמין לחשבון השירות
קודם צריך להקצות את תפקיד האדמין של קבוצת Google Workspace (Group Administrator) לחשבון השירות שרוצים להעביר אליו את הסמכויות, באמצעות Admin SDK Roles and Role Assignments API. בשלב הזה, חשבון השירות מקבל גישה לקבוצות בדומיין, אבל לא למשאבים אחרים.
במדריך לניהול תפקידים מופיע מידע כללי על ניהול תפקידים באמצעות Admin SDK API. כדי להקצות את התפקיד 'אדמין קבוצה' לחשבון השירות, פועלים לפי השלבים הבאים.
נכנסים לדף Service Accounts במסוף Google Cloud .
לוחצים על השם של חשבון השירות שרוצים להשתמש בו עם Groups API.
מעתיקים את המזהה הייחודי של חשבון השירות.
מפעילים את Admin SDK Roles API כדי לזהות את
roleIdעבור Group Administrator. אפשר להשתמש בAPI Explorer בתיעוד של SDK לאדמינים כדי לעשות זאת.מפעילים את Role Assignments API עם גוף הבקשה הבא:
{ "assignedTo": "SERVICE_ACCOUNT_UNIQUE_ID" "roleId": "ROLE_ID" "scopeType": "CUSTOMER" "kind": "admin#directory#roleAssignment" }
אימות והרשאה של חשבון השירות
עכשיו יש לכם חשבון שירות עם תפקיד אדמין בקבוצה. השלב השני הוא להשלים את תהליך האימות באמצעות OAuth עבור חשבון השירות.
אם אתם מפתחים אפליקציה ב- Google Cloud וחשבון השירות הוא בעלים של הפרויקט, אתם יכולים להשתמש בפרטי הכניסה שמוגדרים כברירת מחדל באפליקציה במקום זאת, כדי לפשט את התהליך. מידע נוסף זמין במאמר ביצוע אימות כחשבון שירות.
אם חשבון השירות לא מוגדר כבעלים של הפרויקט, צריך לפעול לפי ההוראות שבהמשך.
בכל מקרה, ההיקף הרלוונטי ל-Cloud Identity Groups API הוא
https://www.googleapis.com/auth/cloud-identity.groups.
באמצעות פרטי הכניסה שיצרתם, יוצרים אסימון גישה.
Java
GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(emailAddress) .setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12")) .setServiceAccountScopes(ImmutableList.of("https://www.googleapis.com/auth/cloud-identity.groups")) .build();Python
from google.oauth2 import service_account SCOPES = ['https://www.googleapis.com/auth/cloud-identity.groups'] SERVICE_ACCOUNT_FILE = '/path/to/service-account-file.json' credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES)המשך
import ( "context" "os" "golang.org/x/oauth2/google" ) ctx := context.Background() jsonKey, err := os.ReadFile("/path/to/service-account-file.json") if err != nil { // Handle error. } conf, err := google.JWTConfigFromJSON(jsonKey, "https://www.googleapis.com/auth/cloud-identity.groups") if err != nil { // Handle error. } ts := conf.TokenSource(ctx)שומרים את אסימון הגישה שנוצר.
קוד מלא ליצירת אסימון גישה לחשבון שירות
Java
GenerateServiceAccountOauth2Token.java
package com.google.tools;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.common.collect.ImmutableList;
import java.io.FileInputStream;
/** Command line tool to generate Oauth2 token for a given service account
/** without domain wide delegation. */
public final class GenerateServiceAccountOauth2Token {
private static final ImmutableList<String> API_SCOPES =
ImmutableList.of(
"https://www.googleapis.com/auth/cloud-identity.groups",
"https://www.googleapis.com/auth/admin.directory.group",
"https://www.googleapis.com/auth/admin.directory.group.member",
"https://www.googleapis.com/auth/apps.groups.settings");
public static void main(final String[] args) throws Exception {
String accessToken = getTokenFromJsonKey();
System.out.println("Token: " + accessToken);
}
private static String getTokenFromJsonKey() throws Exception {
GoogleCredential credential =
GoogleCredential.fromStream(
new FileInputStream(
"<path for json file>"),
new NetHttpTransport(),
GsonFactory.getDefaultInstance());
System.out.println("ServiceAccountId=" + credential.getServiceAccountId());
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
GoogleCredential.Builder builder =
new GoogleCredential.Builder()
.setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
.setServiceAccountPrivateKeyId(credential.getServiceAccountPrivateKeyId())
.setServiceAccountId(credential.getServiceAccountId())
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountScopes(API_SCOPES)
.setClock(credential.getClock());
credential = builder.build();
if (!credential.refreshToken()) {
throw new Exception("Failed to fetch access token.");
}
return credential.getAccessToken();
}
}
יצירת כלל
java_binary(
name = "generate_oauth2_token",
srcs = ["GenerateServiceAccountOauth2Token.java"],
main_class = "com.google.tools.GenerateServiceAccountOauth2Token",
deps = [
"//java/com/google/api/client/googleapis/auth/oauth2",
"//java/com/google/api/client/googleapis/javanet",
"//java/com/google/api/client/http",
"//java/com/google/api/client/http/javanet",
"//java/com/google/common/base",
"//java/com/google/common/collect",
"//third_party/java/google_http_java_client:gson",
"//third_party/java/google_http_java_client:json",
],
)
בדיקת חשבון השירות
מנסים לבצע קריאה ל-Groups API עם פרטי הכניסה של חשבון השירות: ליצור קבוצה, להוסיף משתמשים, לעדכן את הגדרות הקבוצה וכו'.
בודקים את יומני הביקורת בקטע 'דוחות' במסוף Admin של Google. חשבון השירות אמור להופיע כשחקן עבור השינויים שקשורים לקבוצה. מידע נוסף זמין במאמר בנושא אירועים ביומן.
אפשר גם להשתמש בממשקי API כדי לגשת ליומני ביקורת. כדי לבדוק באמצעות כלי ה-API Explorer של Reports API, צריך להשתמש בפרטי הכניסה שלכם לאדמין ב-OAuth.
אימות כחשבון שירות עם הקצאת הרשאות ברמת הדומיין
אם אתם אדמינים שמנהלים קבוצות זהויות, או אם אתם רוצים להעניק לחשבון הרשאות ברמת הדומיין כדי שהוא יוכל לנהל את קבוצות Google בשם האדמינים, אתם צריכים לבצע אימות כחשבון שירות.
פרטים על הגדרת הענקת גישה ברמת הדומיין זמינים במאמר בנושא שליטה בהרשאות הגישה ל-API באמצעות הענקת גישה ברמת הדומיין.
כדי לבצע אימות כחשבון שירות, אפשר לעיין במאמר שימוש ב-OAuth 2.0 לאפליקציות שרת-אל-שרת.
כשמפעילים את פרטי הכניסה בקוד, מציינים את כתובת האימייל שחשבון השירות פועל בה על ידי קריאה ל-with_subject() בפרטי הכניסה.
לדוגמה:
Java
import com.google.auth.oauth2.GoogleCredentials;
GoogleCredentials credentials = GoogleCredentials
.fromStream(new FileInputStream(SERVICE_ACCOUNT_FILE))
.createScoped(SCOPES)
.createDelegated(delegated_email);
Python
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES).with_subject(delegated_email)
המשך
import (
"context"
"os"
"golang.org/x/oauth2/google"
)
ctx := context.Background()
jsonKey, err := os.ReadFile(SERVICE_ACCOUNT_FILE)
if err != nil {
// Handle error.
}
config, err := google.JWTConfigFromJSON(jsonKey, SCOPES...)
if err != nil {
// Handle error.
}
config.Subject = delegated_email
ts := config.TokenSource(ctx)
יצירת מופע של לקוח
בדוגמה הבאה אפשר לראות איך ליצור מופע של לקוח באמצעות פרטי כניסה של חשבון שירות. כדי לבצע אימות כמשתמש קצה במקום זאת, מחליפים את האובייקט credential מחשבון השירות באובייקט credential שקיבלתם קודם במאמר שימוש ב-OAuth 2.0 לאפליקציות שרת אינטרנט.
Java
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.cloudidentity.v1.CloudIdentity;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.FileInputStream;
import java.util.Collections;
import java.util.List;
// ...
List<String> SCOPES = Collections.singletonList("https://www.googleapis.com/auth/cloud-identity.groups");
String SERVICE_ACCOUNT_FILE = "/path/to/service-account-file.json";
public CloudIdentity createService() throws Exception {
GoogleCredentials credentials = GoogleCredentials
.fromStream(new FileInputStream(SERVICE_ACCOUNT_FILE))
.createScoped(SCOPES)
.createDelegated("user@example.org"); // Omit for no domain-wide delegation
CloudIdentity service = new CloudIdentity.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
GsonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credentials))
.setApplicationName("your-app-name")
.build();
return service;
}
Python
from google.oauth2 import service_account
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/cloud-identity.groups']
SERVICE_ACCOUNT_FILE = '/path/to/service-account-file.json'
def create_service():
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_credentials = credentials.with_subject('user@example.org') # Omit for no domain-wide delegation
service_name = 'cloudidentity'
api_version = 'v1'
service = googleapiclient.discovery.build(
service_name,
api_version,
credentials=delegated_credentials)
return service
המשך
import (
"context"
"os"
"golang.org/x/oauth2/google"
"google.golang.org/api/cloudidentity/v1"
"google.golang.org/api/option"
)
// ...
scopes := []string{"https://www.googleapis.com/auth/cloud-identity.groups"}
serviceAccountFile := "/path/to/service-account-file.json"
func createService(ctx context.Context) (*cloudidentity.Service, error) {
jsonKey, err := os.ReadFile(serviceAccountFile)
if err != nil {
return nil, err
}
config, err := google.JWTConfigFromJSON(jsonKey, scopes...)
if err != nil {
return nil, err
}
config.Subject = "user@example.org" // Omit for no domain-wide delegation
ts := config.TokenSource(ctx)
service, err := cloudidentity.NewService(ctx, option.WithTokenSource(ts))
return service, err
}
עכשיו אפשר להתחיל לבצע קריאות ל-Groups API.