1

我正在使用 GoogleDriveAPI 将文档从 Asp.net 上传到 Drive。它工作正常,但我需要使用 ClientID 和 ClientSecret 进行身份验证。不是 gmail 用户名/密码。在进行身份验证后,它会在登录后重定向到 gmail 以进行登录,它要求 Drive 的 AccessPermission。那么我如何才能通过 GmailUserID 和 Password 进行身份验证而不是 ClientID 和 ClientSecret 。之后我可以再次限制 Login for Authorization 。

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using DotNetOpenAuth.OAuth2;
    using Google.Apis.Authentication.OAuth2;
    using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
    using Google.Apis.Drive.v2;
    using Google.Apis.Drive.v2.Data;
    using Google.Apis.Util;
    using System.Diagnostics;
    using DotNetOpenAuth.Messaging;
    using System.Text;
    using System.IO;

    public partial class _Default : System.Web.UI.Page
    {

      private static DriveService driveService;
      private static OAuth2Authenticator<WebServerClient> authenticator;
      private static IAuthorizationState _state;

      String CLIENT_ID = "90994017777728.apps.googleusercontent.com";
      String CLIENT_SECRET = "IR777777773Nf3vnLT0v";

      private static readonly string[] SCOPES = new[] { DriveService.Scopes.Drive.GetStringValue() };

        protected void Page_Load(object sender, EventArgs e)
        {
          Login();
        }

        private IAuthorizationState AuthState {
          get {
            return _state ?? HttpContext.Current.Session["GoogleAuthState"] as IAuthorizationState;
          }
        }

        private OAuth2Authenticator<WebServerClient> CreateAuthenticator() {
          var provider = new WebServerClient(GoogleAuthenticationServer.Description,CLIENT_ID,CLIENT_SECRET);
          var authenticator = new OAuth2Authenticator<WebServerClient>(provider,GetAuthorization);
          return authenticator;
        }

        private IAuthorizationState GetAuthorization(WebServerClient client) {
          IAuthorizationState state = AuthState;
          if (state != null) {
            if (state.AccessTokenExpirationUtc.Value.CompareTo(DateTime.Now.ToUniversalTime()) > 0)
              return state;
            else
              state = null;
          }
          state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
          if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken))) {
            if (state.RefreshToken == null)
              state.RefreshToken = "";
            HttpContext.Current.Session["GoogleAuthState"] = _state = state;
            return state;
          }
          client.RequestUserAuthorization(SCOPES,"",HttpContext.Current.Request.Url); // Redirecting to Gmail LoginPage
          return null;
        }

        private string GetContentType(string fileExtension) {
          if (string.IsNullOrEmpty(fileExtension))
            return string.Empty;

          string contentType = string.Empty;
          switch (fileExtension) {
            case "htm":
            case "html":
              contentType = "text/HTML";
              break;

            case "txt":
              contentType = "text/plain";
              break;

            case "doc":
            case "rtf":
            case "docx":
              contentType = "Application/msword";
              break;

            case "xls":
            case "xlsx":
              contentType = "Application/x-msexcel";
              break;

            case "jpg":
            case "jpeg":
              contentType = "image/jpeg";
              break;
            case "png":
              contentType = "image/png";
              break;
            case "bmp":
              contentType = "image/bmp";
              break;
            case "gif":
              contentType = "image/GIF";
              break;

            case "pdf":
              contentType = "application/pdf";
              break;
          }

          return contentType;
        }

        public void Login() {
          if (authenticator == null)
            authenticator = CreateAuthenticator();
          if (driveService == null) {
            driveService = new DriveService(authenticator);
          }

        }

        protected void Button1_Click(object sender,EventArgs e) {
          string[] stringParts = FileUpload1.FileName.Split(new char[] { '/' });
          string str = stringParts[stringParts.Length - 1].ToString();
          string[] strType = str.Split(new char[] { '.' });
          string type = GetContentType(strType[1]);
          Google.Apis.Drive.v2.Data.File newFile = new Google.Apis.Drive.v2.Data.File { Title = FileUpload1.FileName,MimeType = type };
          byte[] byteArray = FileUpload1.FileBytes;
          MemoryStream stream = new MemoryStream(byteArray);
          FilesResource.InsertMediaUpload request = driveService.Files.Insert(newFile,stream,newFile.MimeType);
          request.Convert = true;
          request.Upload();
          Google.Apis.Drive.v2.Data.File file = request.ResponseBody;
          InsertPermission(driveService,file);
          HttpContext.Current.Session["GoogleAuthState"] = null;
          Response.Write(file.AlternateLink);
        }


        public void InsertPermission(DriveService service,Google.Apis.Drive.v2.Data.File file) {
          Permission newPermission = new Permission();
          newPermission.Value = TextBox1.Text;
          newPermission.Type = "user";
          newPermission.Role = "reader";
          try {
            Permission per = service.Permissions.Insert(newPermission,file.Id).Fetch();
          }
          catch (Exception e) {
            Console.WriteLine("An error occurred: " + e.Message);
          }
        }
4

0 回答 0