public async Task CompleteOAuthFlowTest() { // setup var mockHttp = GetMockHttpMessageHandler(); Server server = new Server { Services = { Publisher.BindService(new PluginSalesforce.Plugin.Plugin(mockHttp.ToHttpClient())) }, Ports = { new ServerPort("localhost", 0, ServerCredentials.Insecure) } }; server.Start(); var port = server.Ports.First().BoundPort; var channel = new Channel($"localhost:{port}", ChannelCredentials.Insecure); var client = new Publisher.PublisherClient(channel); var completeRequest = new CompleteOAuthFlowRequest { Configuration = new OAuthConfiguration { ClientId = "client", ClientSecret = "secret", ConfigurationJson = "{}" }, RedirectUrl = "http://test.com?code=authcode", RedirectBody = "" }; // act var response = client.CompleteOAuthFlow(completeRequest); // assert Assert.IsType <CompleteOAuthFlowResponse>(response); Assert.Contains("mocktoken", response.OauthStateJson); Assert.Contains("mocktoken", response.OauthStateJson); // cleanup await channel.ShutdownAsync(); await server.ShutdownAsync(); }
/// <summary> /// Gets auth token and refresh tokens from auth code /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public override async Task <CompleteOAuthFlowResponse> CompleteOAuthFlow(CompleteOAuthFlowRequest request, ServerCallContext context) { Logger.Info("Getting Auth and Refresh Token..."); // get code from redirect url string code; var uri = new Uri(request.RedirectUrl); try { code = HttpUtility.UrlDecode(HttpUtility.ParseQueryString(uri.Query).Get("code")); } catch (Exception e) { Logger.Error(e, e.Message); throw; } // token url parameters var redirectUrl = String.Format("{0}{1}{2}{3}", uri.Scheme, Uri.SchemeDelimiter, uri.Authority, uri.AbsolutePath); var clientId = request.Configuration.ClientId; var clientSecret = request.Configuration.ClientSecret; var grantType = "authorization_code"; // build token url var tokenUrl = "https://api.hubapi.com/oauth/v1/token"; // build form data request var formData = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("grant_type", grantType), new KeyValuePair <string, string>("client_id", clientId), new KeyValuePair <string, string>("client_secret", clientSecret), new KeyValuePair <string, string>("redirect_uri", redirectUrl), new KeyValuePair <string, string>("code", code) }; var body = new FormUrlEncodedContent(formData); // get tokens var oAuthState = new OAuthState(); try { // var client = _injectedClient; var client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.PostAsync(tokenUrl, body); response.EnsureSuccessStatusCode(); var content = JsonConvert.DeserializeObject <TokenResponse>(await response.Content.ReadAsStringAsync()); oAuthState.AuthToken = content.AccessToken; oAuthState.RefreshToken = content.RefreshToken; oAuthState.Config = JsonConvert.SerializeObject(new OAuthConfig { RedirectUri = redirectUrl }); if (String.IsNullOrEmpty(oAuthState.RefreshToken)) { throw new Exception("Response did not contain a refresh token"); } } catch (Exception e) { Logger.Error(e, e.Message); throw; } // return oauth state json var oAuthResponse = new CompleteOAuthFlowResponse { OauthStateJson = JsonConvert.SerializeObject(oAuthState) }; Logger.Info("Got Auth Token and Refresh Token"); return(oAuthResponse); }
/// <summary> /// Gets auth token and refresh tokens from auth code /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public override async Task <CompleteOAuthFlowResponse> CompleteOAuthFlow(CompleteOAuthFlowRequest request, ServerCallContext context) { Logger.SetLogPrefix("complete_oauth"); Logger.Info("Getting Auth and Refresh Token..."); // get code from redirect url string code; var uri = new Uri(request.RedirectUrl); try { code = HttpUtility.ParseQueryString(uri.Query).Get("code"); } catch (Exception e) { Logger.Error(e, e.Message); throw; } // token url parameters var redirectUrl = String.Format("{0}{1}{2}{3}", uri.Scheme, Uri.SchemeDelimiter, uri.Authority, uri.AbsolutePath); var clientId = request.Configuration.ClientId; var clientSecret = request.Configuration.ClientSecret; var grantType = "authorization_code"; // build token url var tokenUrl = String.Format( "https://accounts.zoho.com/oauth/v2/token?code={0}&redirect_uri={1}&client_id={2}&client_secret={3}&grant_type={4}", code, redirectUrl, clientId, clientSecret, grantType ); // get tokens var oAuthState = new OAuthState(); try { var response = await _injectedClient.PostAsync(tokenUrl, null); response.EnsureSuccessStatusCode(); var content = JsonConvert.DeserializeObject <TokenResponse>(await response.Content.ReadAsStringAsync()); oAuthState.AuthToken = content.access_token; oAuthState.RefreshToken = content.refresh_token; if (String.IsNullOrEmpty(oAuthState.RefreshToken)) { throw new Exception("Response did not contain a refresh token"); } } catch (Exception e) { Logger.Error(e, e.Message); throw; } // return oauth state json var oAuthResponse = new CompleteOAuthFlowResponse { OauthStateJson = JsonConvert.SerializeObject(oAuthState) }; Logger.Info("Got Auth Token and Refresh Token"); return(oAuthResponse); }