Creating a ServiceAccountCredential for a user from a Systems account

孤街醉人 提交于 2019-12-11 02:17:31

问题


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, 
});

回答1:


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.



来源:https://stackoverflow.com/questions/43256237/creating-a-serviceaccountcredential-for-a-user-from-a-systems-account

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!