C# 开发 Google Workspace 用户新增 API (使用 OAuth 2.0)
2025-04-25 15:52:23
准备工作
在 Google Cloud Console 中创建项目并启用 "Admin SDK" API, 然后创建 OAuth 2.0 凭据(选择"桌面应用"类型)并下载JSON文件
必要的 NuGet 包
Google.Apis.Auth
Google.Apis.Admin.Directory.directory_v1
Google.Apis.Auth.Mvc (可选,用于 Web 应用)
Newtonsoft.Json (用于 JSON 处理)
OAuth 2.0 认证流程
C#
public static async Task<DirectoryService> AuthenticateAsync()
{
try
{
Console.WriteLine("[1] 开始认证流程");
// 1. 检查客户端凭据文件
string credPath = "client_secret.json";
Console.WriteLine($"[2] 检查文件: {Path.GetFullPath(credPath)}");
if (!File.Exists(credPath))
{
throw new FileNotFoundException("客户端凭据文件未找到");
}
// 2. 加载客户端凭据
using (var stream = new FileStream(credPath, FileMode.Open, FileAccess.Read))
{
Console.WriteLine("[3] 正在加载客户端凭据...");
var clientSecrets = await GoogleClientSecrets.FromStreamAsync(stream);
// 3. 设置存储路径
string storePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"MyAppAuthStore"
);
Console.WriteLine($"[4] 令牌存储路径: {storePath}");
// 4. 执行授权
Console.WriteLine("[5] 正在启动OAuth授权...");
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
clientSecrets.Secrets,
new[] { DirectoryService.Scope.AdminDirectoryUser },
"user",
CancellationToken.None,
new FileDataStore(storePath, fullPath: true));
Console.WriteLine("[6] OAuth授权完成!"); // 检查是否能执行到这里
// 5. 创建服务实例
Console.WriteLine("[7] 正在初始化DirectoryService...");
return new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Google Workspace User Creation",
});
}
}
catch (Exception ex)
{
Console.WriteLine($"[ERROR] 认证失败: {ex}");
throw;
}
}
创建新用户
C#
public static User CreateUser(DirectoryService service, string domain, NewUserDetails userDetails)
{
User newUser = new User()
{
PrimaryEmail = $"{userDetails.Username}@{domain}",
Name = new UserName()
{
GivenName = userDetails.FirstName,
FamilyName = userDetails.LastName,
FullName = $"{userDetails.FirstName} {userDetails.LastName}"
},
Password = userDetails.Password,
ChangePasswordAtNextLogin = true
};
// 可选: 设置组织单位
if (!string.IsNullOrEmpty(userDetails.OrgUnitPath))
{
newUser.OrgUnitPath = userDetails.OrgUnitPath;
}
try
{
var request = service.Users.Insert(newUser);
return request.Execute();
}
catch (Exception ex)
{
Console.WriteLine($"创建用户时出错: {ex.Message}");
return null;
}
}
End