/// <summary> /// Exchange an authorization code for OAuth 2.0 credentials. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for OAuth 2.0 credentials.</param> /// <returns>OAuth 2.0 credentials.</returns> /// <exception cref="CodeExchangeException">An error occurred.</exception> static IAuthorizationState ExchangeCode(String authorizationCode, OPEN_AUTH_CLIENT clientCredentials) { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, clientCredentials.CLIENT_ID, clientCredentials.CLIENT_SECRET); IAuthorizationState state = new AuthorizationState(); state.Callback = new Uri(clientCredentials.REDIRECT_URI); try { state = provider.ProcessUserAuthorization(authorizationCode, state); return(state); } catch (ProtocolException) { throw new CodeExchangeException(null); } }
/// <summary> /// Retrieve the authorization URL. /// </summary> /// <param name="emailAddress">User's e-mail address.</param> /// <param name="state">State for the authorization URL.</param> /// <returns>Authorization URL to redirect the user to.</returns> public static String GetAuthorizationUrl(String emailAddress, String state, OPEN_AUTH_CLIENT clientCredentials) { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = clientCredentials.CLIENT_ID; IAuthorizationState authorizationState = new AuthorizationState(clientCredentials.SCOPES); authorizationState.Callback = new Uri(clientCredentials.REDIRECT_URI); UriBuilder builder = new UriBuilder(provider.RequestUserAuthorization(authorizationState)); NameValueCollection queryParameters = HttpUtility.ParseQueryString(builder.Query); queryParameters.Set("access_type", "offline"); queryParameters.Set("approval_prompt", "force"); queryParameters.Set("user_id", emailAddress); queryParameters.Set("state", state); builder.Query = queryParameters.ToString(); return(builder.Uri.ToString()); }
protected override void ProcessRequest(System.Net.HttpListenerContext context) { context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); context.Response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); context.Response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); context.Response.Headers.Add("Cache-Control", "no-cache, no-store"); context.Response.AddHeader("Pragma", "no-cache"); context.Response.AddHeader("Pragma", "no-store"); context.Response.AddHeader("cache-control", "no-cache"); string result = string.Empty, file_id = string.Empty, content_type = "application/json; charset=utf-8"; //content_type = "text/html; charset=utf-8"; byte[] buf = null; try { switch (context.Request.Url.LocalPath) { case "/favicon.ico": break; /////////////////////////////////////////////////////////////////// // GET case "/GET_USER_INFO": result = this._gooDriver.f_get_userInfo(); break; case "/GET_RETRIEVE_ALL_FILES": result = this._gooDriver.f_get_retrieveAllFiles(); break; case "/GET_FILE": file_id = context.Request.QueryString["file_id"]; result = this._gooDriver.f_downloadFile(file_id); break; /////////////////////////////////////////////////////////////////// // POST case "/POST_CREATE_TOKEN_NEW": buf = ReadFully(context.Request.InputStream); if (buf.Length > 0) { string json = Encoding.UTF8.GetString(buf); OPEN_AUTH_CLIENT clientCredentials = JsonConvert.DeserializeObject <OPEN_AUTH_CLIENT>(json); result = this._gooDriver.f_create_TokenNew(clientCredentials); } else { result = JsonConvert.SerializeObject(new { Ok = false, Message = "The data to POST must be not null" }); } break; case "/POST_GET_USER_INFO_OR_CREATE_NEW_IF_NOT_EXIST": buf = ReadFully(context.Request.InputStream); if (buf.Length > 0) { string json = Encoding.UTF8.GetString(buf); OPEN_AUTH_CLIENT clientCredentials = JsonConvert.DeserializeObject <OPEN_AUTH_CLIENT>(json); result = this._gooDriver.f_get_userInfoOrCreateNewIfNotExist(clientCredentials); } else { result = JsonConvert.SerializeObject(new { Ok = false, Message = "The data to POST must be not null" }); } break; case "/POST_UPLOAD_FILE": buf = ReadFully(context.Request.InputStream); if (buf.Length > 0) { string json = Encoding.UTF8.GetString(buf); DriveFile df = JsonConvert.DeserializeObject <DriveFile>(json); result = this._gooDriver.f_uploadFile(df); } else { result = JsonConvert.SerializeObject(new { Ok = false, Message = "The data to POST must be not null" }); } break; case "/POST_UPDATE_FILE": buf = ReadFully(context.Request.InputStream); if (buf.Length > 0) { string json = Encoding.UTF8.GetString(buf); DriveFile df = JsonConvert.DeserializeObject <DriveFile>(json); result = this._gooDriver.f_updateFile(df); } break; } } catch (Exception e) { result = JsonConvert.SerializeObject(new { Ok = false, Message = e.Message }); } byte[] bOutput = Encoding.UTF8.GetBytes(result); context.Response.ContentType = content_type; context.Response.ContentLength64 = bOutput.Length; context.Response.OutputStream.Write(bOutput, 0, bOutput.Length); context.Response.OutputStream.Close(); }
/// <summary> /// Retrieve an IAuthenticator instance using the provided state. /// </summary> /// <param name="credentials">OAuth 2.0 credentials to use.</param> /// <returns>Authenticator using the provided OAuth 2.0 credentials</returns> public static IAuthenticator GetAuthenticatorFromState(IAuthorizationState credentials, OPEN_AUTH_CLIENT ClientCredentials) { var provider = new StoredStateClient(GoogleAuthenticationServer.Description, ClientCredentials.CLIENT_ID, ClientCredentials.CLIENT_SECRET, credentials); var auth = new OAuth2Authenticator <StoredStateClient>(provider, StoredStateClient.GetState); auth.LoadAccessToken(); return(auth); }
/// <summary> /// Retrieve credentials using the provided authorization code. /// /// This function exchanges the authorization code for an access token and /// queries the UserInfo API to retrieve the user's e-mail address. If a /// refresh token has been retrieved along with an access token, it is stored /// in the application database using the user's e-mail address as key. If no /// refresh token has been retrieved, the function checks in the application /// database for one and returns it if found or throws a NoRefreshTokenException /// with the authorization URL to redirect the user to. /// </summary> /// <param name="authorizationCode">Authorization code to use to retrieve an access token.</param> /// <param name="state">State to set to the authorization URL in case of error.</param> /// <returns>OAuth 2.0 credentials instance containing an access and refresh token.</returns> /// <exception cref="CodeExchangeException"> /// An error occurred while exchanging the authorization code. /// </exception> /// <exception cref="NoRefreshTokenException"> /// No refresh token could be retrieved from the available sources. /// </exception> public static IAuthenticator GetCredentials(String authorizationCode, String state, OPEN_AUTH_CLIENT clientCredentials) { String emailAddress = ""; try { IAuthorizationState credentials = ExchangeCode(authorizationCode, clientCredentials); Userinfo userInfo = GetUserInfo(credentials, clientCredentials); String userId = userInfo.Id; emailAddress = userInfo.Email; if (!String.IsNullOrEmpty(credentials.RefreshToken)) { StoreCredentials(userId, credentials); return(GetAuthenticatorFromState(credentials, clientCredentials)); } else { credentials = GetStoredCredentials(userId); if (credentials != null && !String.IsNullOrEmpty(credentials.RefreshToken)) { return(GetAuthenticatorFromState(credentials, clientCredentials)); } } } catch (CodeExchangeException e) { Console.WriteLine("An error occurred during code exchange."); // Drive apps should try to retrieve the user and credentials for the current // session. // If none is available, redirect the user to the authorization URL. e.AuthorizationUrl = GetAuthorizationUrl(emailAddress, state, clientCredentials); throw e; } catch (NoUserIdException) { Console.WriteLine("No user ID could be retrieved."); } // No refresh token has been retrieved. String authorizationUrl = GetAuthorizationUrl(emailAddress, state, clientCredentials); throw new NoRefreshTokenException(authorizationUrl); }
/// <summary> /// Send a request to the UserInfo API to retrieve the user's information. /// </summary> /// <param name="credentials">OAuth 2.0 credentials to authorize the request.</param> /// <returns>User's information.</returns> /// <exception cref="NoUserIdException">An error occurred.</exception> public static Userinfo GetUserInfo(IAuthorizationState credentials, OPEN_AUTH_CLIENT clientCredentials) { return(GetUserInfo(GetAuthenticatorFromState(credentials, clientCredentials))); }