问题描述
我使用以下代码通过系统登录(全域身份验证)代表用户执行操作.我发现的唯一实现此目的的示例使用反射来设置用户.我知道这不是完成此任务的正确方法,所以我想知道是否有人可以通过示例解决此问题的方法来帮助我
ServiceAccountCredential credential =
GoogleCredential.FromJson(GOOGLE_SYSTEM_USER_AUTH_INFORMATION)
.CreateScoped(Scopes)
.UnderlyingCredential as ServiceAccountCredential;
var userField = typeof(ServiceAccountCredential).GetField("user",
BindingFlags.NonPublic | BindingFlags.Instance);
userField?.SetValue(credential, GOOGLE_CALENDAR_USERNAME); //Act in the guise of the normal user GOOGLE_CALENDAR_USERNAME
service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
在这里,我将通过ServiceAccountCredential.Initializer
设置作用域和新用户:
ServiceAccountCredential original = (ServiceAccountCredential)
GoogleCredential.FromJson(GOOGLE_SYSTEM_USER_AUTH_INFORMATION).UnderlyingCredential;
var initializer = new ServiceAccountCredential.Initializer(original.Id)
{
User = GOOGLE_CALENDAR_USERNAME,
Key = original.Key,
Scopes = Scopes
};
var credentialForUser = new ServiceAccountCredential(initializer);
现在为您提供ServiceAccountCredential
而不是GoogleCredential
.那就是您当前的代码所使用的,所以应该没问题-但是如果也有一种简单的方法来获取GoogleCredential
,那就太好了.我们应该使这一切变得更简单-我已经为此提出了问题. >
I use the following code to act on behalf of a user through a System-login (domain-wide authenticated). The only example I found which accomplishes this uses reflection to set the user. I know this isn't the proper way to accomplish this so I was wondering if someone could help me out with an example of how this should be solved
ServiceAccountCredential credential =
GoogleCredential.FromJson(GOOGLE_SYSTEM_USER_AUTH_INFORMATION)
.CreateScoped(Scopes)
.UnderlyingCredential as ServiceAccountCredential;
var userField = typeof(ServiceAccountCredential).GetField("user",
BindingFlags.NonPublic | BindingFlags.Instance);
userField?.SetValue(credential, GOOGLE_CALENDAR_USERNAME); //Act in the guise of the normal user GOOGLE_CALENDAR_USERNAME
service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
Here's how I'd do it, setting both the scopes and the new user at the same time via the ServiceAccountCredential.Initializer
:
ServiceAccountCredential original = (ServiceAccountCredential)
GoogleCredential.FromJson(GOOGLE_SYSTEM_USER_AUTH_INFORMATION).UnderlyingCredential;
var initializer = new ServiceAccountCredential.Initializer(original.Id)
{
User = GOOGLE_CALENDAR_USERNAME,
Key = original.Key,
Scopes = Scopes
};
var credentialForUser = new ServiceAccountCredential(initializer);
Now that gives you a ServiceAccountCredential
rather than a GoogleCredential
. That's what your current code uses, so it should be okay - but it would be nice if there were a simple way of getting a GoogleCredential
for this too. We should make this all simpler - I've filed an issue for that.
这篇关于从系统帐户为用户创建ServiceAccountCredential的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!