/// <summary> /// Do the actual upload to OneDrive /// </summary> /// <param name="oAuth2Settings">OAuth2Settings</param> /// <param name="surfaceToUpload">ISurface to upload</param> /// <param name="progress">IProgress</param> /// <param name="token">CancellationToken</param> /// <returns>OneDriveUploadResponse with details</returns> private async Task <OneDriveUploadResponse> UploadToOneDriveAsync(OAuth2Settings oAuth2Settings, ISurface surfaceToUpload, IProgress <int> progress = null, CancellationToken token = default) { var filename = surfaceToUpload.GenerateFilename(CoreConfiguration, _oneDriveConfiguration); var uploadUri = OneDriveUri.AppendSegments("root:", "Screenshots", filename + ":", "content"); var localBehaviour = _oneDriveHttpBehaviour.ShallowClone(); if (progress != null) { localBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100)), token); }; } var oauthHttpBehaviour = OAuth2HttpBehaviourFactory.Create(oAuth2Settings, localBehaviour); using (var imageStream = new MemoryStream()) { surfaceToUpload.WriteToStream(imageStream, CoreConfiguration, _oneDriveConfiguration); imageStream.Position = 0; using (var content = new StreamContent(imageStream)) { content.Headers.Add("Content-Type", surfaceToUpload.GenerateMimeType(CoreConfiguration, _oneDriveConfiguration)); oauthHttpBehaviour.MakeCurrent(); return(await uploadUri.PutAsync <OneDriveUploadResponse>(content, token)); } } }
public BoxDestination(IBoxConfiguration boxConfiguration, IBoxLanguage boxLanguage) { _boxConfiguration = boxConfiguration; _boxLanguage = boxLanguage; _oauth2Settings = new OAuth2Settings { AuthorizationUri = new Uri("https://app.box.com"). AppendSegments("api", "oauth2", "authorize"). ExtendQuery(new Dictionary <string, string> { { "response_type", "code" }, { "client_id", "{ClientId}" }, { "redirect_uri", "{RedirectUrl}" }, { "state", "{State}" } }), TokenUrl = new Uri("https://api.box.com/oauth2/token"), CloudServiceName = "Box", ClientId = boxConfiguration.ClientId, ClientSecret = boxConfiguration.ClientSecret, RedirectUrl = "https://www.box.com/home/", AuthorizeMode = AuthorizeModes.EmbeddedBrowser, Token = boxConfiguration }; }
public InfoPlusApplication(string code, string secret, string scope, string authUri, bool release, long minVersion, long maxVersion) { if (false == code.Contains("@")) { code = code + "@" + ApplicationSettings.DefaultDomain; } this.fullCode = code; this.Secret = secret; this.Scope = scope; this.Release = release; this.MinVersion = minVersion; this.MaxVersion = maxVersion; if (false == string.IsNullOrEmpty(authUri)) { var settings = new OAuth2Settings(); settings.ConsumerKey = this.fullCode; settings.ConsumerSecret = this.Secret; if (false == authUri.EndsWith("/")) { authUri += "/"; } settings.EndPointAuthorize = authUri + "auth"; settings.EndPointToken = authUri + "token"; this.OAuth2 = new OAuth2Consumer(settings); } }
public BoxDestination( ICoreConfiguration coreConfiguration, IGreenshotLanguage greenshotLanguage, IBoxConfiguration boxConfiguration, IBoxLanguage boxLanguage, Func <CancellationTokenSource, Owned <PleaseWaitForm> > pleaseWaitFormFactory, INetworkConfiguration networkConfiguration, IResourceProvider resourceProvider) : base(coreConfiguration, greenshotLanguage) { _boxConfiguration = boxConfiguration; _boxLanguage = boxLanguage; _pleaseWaitFormFactory = pleaseWaitFormFactory; _networkConfiguration = networkConfiguration; _resourceProvider = resourceProvider; _oauth2Settings = new OAuth2Settings { AuthorizationUri = new Uri("https://app.box.com"). AppendSegments("api", "oauth2", "authorize"). ExtendQuery(new Dictionary <string, string> { { "response_type", "code" }, { "client_id", "{ClientId}" }, { "redirect_uri", "{RedirectUrl}" }, { "state", "{State}" } }), TokenUrl = new Uri("https://api.box.com/oauth2/token"), CloudServiceName = "Box", ClientId = boxConfiguration.ClientId, ClientSecret = boxConfiguration.ClientSecret, RedirectUrl = "https://www.box.com/home/", AuthorizeMode = AuthorizeModes.EmbeddedBrowser, Token = boxConfiguration }; }
public GooglePhotosDestination(IGooglePhotosConfiguration googlePhotosConfiguration, IGooglePhotosLanguage googlePhotosLanguage) { _googlePhotosConfiguration = googlePhotosConfiguration; _googlePhotosLanguage = googlePhotosLanguage; _oAuth2Settings = new OAuth2Settings { AuthorizationUri = new Uri("https://accounts.google.com").AppendSegments("o", "oauth2", "auth"). ExtendQuery(new Dictionary <string, string> { { "response_type", "code" }, { "client_id", "{ClientId}" }, { "redirect_uri", "{RedirectUrl}" }, { "state", "{State}" }, { "scope", "https://picasaweb.google.com/data/" } }), TokenUrl = new Uri("https://www.googleapis.com/oauth2/v3/token"), CloudServiceName = "GooglePhotos", ClientId = googlePhotosConfiguration.ClientId, ClientSecret = googlePhotosConfiguration.ClientSecret, RedirectUrl = "http://getgreenshot.org", AuthorizeMode = AuthorizeModes.LocalhostServer, Token = googlePhotosConfiguration }; }
public ImgurOAuth2Tests(ITestOutputHelper testOutputHelper) { LogSettings.RegisterDefaultLogger <XUnitLogger>(LogLevels.Verbose, testOutputHelper); var oAuth2Settings = new OAuth2Settings { AuthorizationUri = ApiUri.AppendSegments("oauth2", "authorize"). ExtendQuery(new Dictionary <string, string> { { "response_type", "code" }, { "client_id", "{ClientId}" }, { "redirect_uri", "{RedirectUrl}" }, // TODO: Add version? { "state", "{State}" } }), TokenUrl = ApiUri.AppendSegments("oauth2", "token"), CloudServiceName = "Imgur", ClientId = ClientId, ClientSecret = ClientSecret, RedirectUrl = "https://getgreenshot.org/oauth/imgur", AuthorizeMode = AuthorizeModes.OutOfBoundAuto }; var behavior = new HttpBehaviour { JsonSerializer = new JsonNetJsonSerializer(), OnHttpClientCreated = httpClient => { httpClient.SetAuthorization("Client-ID", ClientId); httpClient.DefaultRequestHeaders.ExpectContinue = false; } }; _oAuthHttpBehaviour = OAuth2HttpBehaviourFactory.Create(oAuth2Settings, behavior); }
public DropboxDestination(IDropboxConfiguration dropboxPluginConfiguration, IDropboxLanguage dropboxLanguage) { _dropboxPluginConfiguration = dropboxPluginConfiguration; _dropboxLanguage = dropboxLanguage; _oAuth2Settings = new OAuth2Settings { AuthorizationUri = DropboxApiUri. AppendSegments("1", "oauth2", "authorize"). ExtendQuery(new Dictionary <string, string> { { "response_type", "code" }, { "client_id", "{ClientId}" }, { "redirect_uri", "{RedirectUrl}" }, { "state", "{State}" } }), TokenUrl = DropboxApiUri.AppendSegments("1", "oauth2", "token"), CloudServiceName = "Dropbox", ClientId = dropboxPluginConfiguration.ClientId, ClientSecret = dropboxPluginConfiguration.ClientSecret, AuthorizeMode = AuthorizeModes.LocalhostServer, RedirectUrl = "http://localhost:47336", Token = dropboxPluginConfiguration }; _oAuthHttpBehaviour = OAuth2HttpBehaviourFactory.Create(_oAuth2Settings); }
/// <summary> /// Create a specify OAuth2 IHttpBehaviour /// </summary> /// <param name="oAuth2Settings">OAuth2Settings</param> /// <param name="fromHttpBehaviour">IHttpBehaviour to clone, null if a new needs to be generated</param> /// <returns>IHttpBehaviour</returns> public static IHttpBehaviour Create(OAuth2Settings oAuth2Settings, IHttpBehaviour fromHttpBehaviour = null) { // Get a clone of a IHttpBehaviour (passed or current) var oauthHttpBehaviour = (fromHttpBehaviour ?? HttpBehaviour.Current).ShallowClone(); // Add a wrapper (delegate handler) which wraps all new HttpMessageHandlers oauthHttpBehaviour.ChainOnHttpMessageHandlerCreated(httpMessageHandler => new OAuth2HttpMessageHandler(oAuth2Settings, oauthHttpBehaviour, httpMessageHandler)); return oauthHttpBehaviour; }
/// <summary> /// Create a specify OAuth2 IHttpBehaviour /// </summary> /// <param name="oAuth2Settings">OAuth2Settings</param> /// <param name="fromHttpBehaviour">IHttpBehaviour to clone, null if a new needs to be generated</param> /// <returns>IChangeableHttpBehaviour</returns> public static IChangeableHttpBehaviour Create(OAuth2Settings oAuth2Settings, IHttpBehaviour fromHttpBehaviour = null) { // Get a clone of a IHttpBehaviour (passed or current) var oauthHttpBehaviour = (fromHttpBehaviour ?? HttpBehaviour.Current).ShallowClone(); // Add a wrapper (delegate handler) which wraps all new HttpMessageHandlers oauthHttpBehaviour.ChainOnHttpMessageHandlerCreated(httpMessageHandler => new OAuth2HttpMessageHandler(oAuth2Settings, oauthHttpBehaviour, httpMessageHandler)); return(oauthHttpBehaviour); }
/// <summary> /// Put string /// </summary> /// <param name="url"></param> /// <param name="content"></param> /// <param name="settings">OAuth2Settings</param> /// <returns>response</returns> public static string HttpPut(string url, string content, OAuth2Settings settings) { var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.PUT, url, settings); byte[] data = Encoding.UTF8.GetBytes(content); using (var requestStream = webRequest.GetRequestStream()) { requestStream.Write(data, 0, data.Length); } return(NetworkHelper.GetResponseAsString(webRequest)); }
/// <summary> /// Do the actual upload to Box /// For more details on the available parameters, see: http://developers.box.net/w/page/12923951/ApiFunction_Upload%20and%20Download /// </summary> /// <param name="image">Image for box upload</param> /// <param name="title">Title of box upload</param> /// <param name="filename">Filename of box upload</param> /// <returns>url to uploaded image</returns> public static string UploadToBox(SurfaceContainer image, string title, string filename) { // Fill the OAuth2Settings var settings = new OAuth2Settings { AuthUrlPattern = "https://app.box.com/api/oauth2/authorize?client_id={ClientId}&response_type=code&state={State}&redirect_uri={RedirectUrl}", TokenUrl = "https://api.box.com/oauth2/token", CloudServiceName = "Box", ClientId = BoxCredentials.ClientId, ClientSecret = BoxCredentials.ClientSecret, RedirectUrl = "https://www.box.com/home/", BrowserSize = new Size(1060, 600), AuthorizeMode = OAuth2AuthorizeMode.EmbeddedBrowser, RefreshToken = Config.RefreshToken, AccessToken = Config.AccessToken, AccessTokenExpires = Config.AccessTokenExpires }; // Copy the settings from the config, which is kept in memory and on the disk try { var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, UploadFileUri, settings); IDictionary <string, object> parameters = new Dictionary <string, object>(); parameters.Add("file", image); parameters.Add("parent_id", Config.FolderId); NetworkHelper.WriteMultipartFormData(webRequest, parameters); var response = NetworkHelper.GetResponseAsString(webRequest); Log.DebugFormat("Box response: {0}", response); var upload = JsonSerializer.Deserialize <Upload>(response); if (upload?.Entries == null || upload.Entries.Count == 0) { return(null); } if (Config.UseSharedLink) { string filesResponse = HttpPut(string.Format(FilesUri, upload.Entries[0].Id), "{\"shared_link\": {\"access\": \"open\"}}", settings); var file = JsonSerializer.Deserialize <FileEntry>(filesResponse); return(file.SharedLink.Url); } return($"http://www.box.com/files/0/f/0/1/f_{upload.Entries[0].Id}"); } finally { // Copy the settings back to the config, so they are stored. Config.RefreshToken = settings.RefreshToken; Config.AccessToken = settings.AccessToken; Config.AccessTokenExpires = settings.AccessTokenExpires; Config.IsDirty = true; IniConfig.Save(); } }
public void OAuth2Settings_Validate_RequiresCredentialProviderForClientCredentialsGrant() { var settings = new OAuth2Settings(); settings.GrantType = OAuth2GrantTypes.ClientCredentials; settings.AccessTokenUrl = new Uri("http://testsite.com/access_token"); settings.AuthorizeUrl = new Uri("http://testsite.com/authorize"); settings.RedirectUrl = new Uri("http://testsite.com/redirect"); settings.ClientCredentialProvider = null; settings.Validate(); }
/// <summary> /// Initializes a new instance of the <see cref="RestApiDemo" /> class. /// </summary> public RestApiDemo(string clientId, string clientSecret) { this.oauthSettings = new OAuth2Settings { ClientId = clientId, ClientSecret = clientSecret, AccessTokenUrl = "https://apps.xynaps.net/api/v1/oauth2/token", BaseUrl = "https://apps.xynaps.net/" }; this.client = new OAuthHttpClient(this.oauthSettings); }
public AuthorizeService( IFindApplicationService findApplicationService, IAuthenticateUserService authenticateUserService, IAuthorizationCodeRepository authorizationCodeRepository, IPasswordGenerator passwordGenerator, OAuth2Settings settings) { _findApplicationService = findApplicationService; _authenticateUserService = authenticateUserService; _authorizationCodeRepository = authorizationCodeRepository; _passwordGenerator = passwordGenerator; _settings = settings; }
private async Task <OneDriveGetLinkResponse> CreateSharableLinkAync(OAuth2Settings oAuth2Settings, string imageId, OneDriveLinkType oneDriveLinkType) { var sharableLink = OneDriveUri.AppendSegments("items", imageId, "createLink"); var localBehaviour = _oneDriveHttpBehaviour.ShallowClone(); var oauthHttpBehaviour = OAuth2HttpBehaviourFactory.Create(oAuth2Settings, localBehaviour); oauthHttpBehaviour.MakeCurrent(); var body = new OneDriveGetLinkRequest(); body.Scope = oneDriveLinkType == OneDriveLinkType.@public ? "anonymous" : "organization"; body.Type = "view"; return(await sharableLink.PostAsync <OneDriveGetLinkResponse>(body)); }
public RefreshTokenGenerator( IAuthenticateClientService applicationService, IRefreshTokenRepository refreshTokenRepository, IAccessTokenRepository accessTokenRepository, IJwtTokenFactory jwtTokenFactory, IPasswordGenerator passwordGenerator, OAuth2Settings settings) { _authenticateClientService = applicationService; _refreshTokenRepository = refreshTokenRepository; _accessTokenRepository = accessTokenRepository; _jwtTokenFactory = jwtTokenFactory; _passwordGenerator = passwordGenerator; _settings = settings; }
public void OAuth2Settings_Validate_RequiresAuthenticationCallbackForAuthorizationGrant() { var settings = new OAuth2Settings(); settings.GrantType = OAuth2GrantTypes.AuthorizationCode; settings.AccessTokenUrl = new Uri("http://testsite.com/access_token"); settings.AuthorizeUrl = new Uri("http://testsite.com/authorize"); settings.RedirectUrl = new Uri("http://testsite.com/redirect"); settings.ClientCredentialProvider = new SimpleCredentialProvider(new SimpleCredentials() { Secret = "A", Identifier = "B" }); settings.RequestAuthentication = null; settings.Validate(); }
public void OAuth2Settings_Validate_ThrowsOnNullAuthorizeUrl() { var settings = new OAuth2Settings(); settings.GrantType = OAuth2GrantTypes.AuthorizationCode; settings.AccessTokenUrl = new Uri("http://testsite.com/access_token"); settings.AuthorizeUrl = null; settings.RedirectUrl = new Uri("http://testsite.com/redirect"); settings.RequestAuthentication = (authUri) => { return(Task.FromResult(new AuthorisationCodeResponse())); }; settings.ClientCredentialProvider = new SimpleCredentialProvider(new SimpleCredentials() { Secret = "A", Identifier = "B" }); settings.Validate(); }
public void CanGetCurrentOAuth2Settings() { // Arrange Request protectedResourceRequest = Session.Bind(OAuth2TestConstants.ProtectedResourcePath); // Act OAuth2Settings settings1 = Session.OAuth2_GetSettings(); Session.OAuth2_Configure(GetSettings()) .OAuth2_GetAccessTokenUsingOwnerUsernamePassword(OAuth2TestConstants.Username, OAuth2TestConstants.UserPassword); OAuth2Settings settings2 = Session.OAuth2_GetSettings(); // Assert Assert.IsNull(settings1); Assert.IsNotNull(settings2); }
static void Setup() { // Create new session with implicit service Session = RamoneConfiguration.NewSession(new Uri(GoogleAPIBaseUrl)); // Get Google API keys from file (don't want the secret parts hardcoded in public repository) GoogleKeys keys = new GoogleKeys(); if (SelectedAccessType != AccessType.JWT) { keys = ReadKeys(); } // Configure OAuth2 with the stuff it needs for it's magic OAuth2Settings settings = new OAuth2Settings { TokenEndpoint = new Uri(TokenEndpointUrl) }; if (SelectedAccessType == AccessType.PinCode) { settings.AuthorizationEndpoint = new Uri(AuthorizationEndpointUrl); settings.RedirectUri = new Uri("urn:ietf:wg:oauth:2.0:oob"); settings.ClientID = keys.ClientId; settings.ClientSecret = keys.ClientSecret; settings.ClientAuthenticationMethod = OAuth2Settings.DefaultClientAuthenticationMethods.RequestBody; } else if (SelectedAccessType == AccessType.Redirect) { settings.AuthorizationEndpoint = new Uri(AuthorizationEndpointUrl); settings.RedirectUri = new Uri("http://localhost"); settings.ClientID = keys.ClientId; settings.ClientSecret = keys.ClientSecret; settings.ClientAuthenticationMethod = OAuth2Settings.DefaultClientAuthenticationMethods.RequestBody; } else { settings.ClientAuthenticationMethod = OAuth2Settings.DefaultClientAuthenticationMethods.Other; } Session.OAuth2_Configure(settings); }
public DropboxDestination( IDropboxConfiguration dropboxPluginConfiguration, IDropboxLanguage dropboxLanguage, INetworkConfiguration networkConfiguration, IResourceProvider resourceProvider, ICoreConfiguration coreConfiguration, IGreenshotLanguage greenshotLanguage, Func <CancellationTokenSource, Owned <PleaseWaitForm> > pleaseWaitFormFactory ) : base(coreConfiguration, greenshotLanguage) { _dropboxPluginConfiguration = dropboxPluginConfiguration; _dropboxLanguage = dropboxLanguage; _resourceProvider = resourceProvider; _pleaseWaitFormFactory = pleaseWaitFormFactory; _oAuth2Settings = new OAuth2Settings { AuthorizationUri = DropboxApiUri. AppendSegments("1", "oauth2", "authorize"). ExtendQuery(new Dictionary <string, string> { { "response_type", "code" }, { "client_id", "{ClientId}" }, { "redirect_uri", "{RedirectUrl}" }, { "state", "{State}" } }), TokenUrl = DropboxApiUri.AppendSegments("1", "oauth2", "token"), CloudServiceName = "Dropbox", ClientId = dropboxPluginConfiguration.ClientId, ClientSecret = dropboxPluginConfiguration.ClientSecret, AuthorizeMode = AuthorizeModes.LocalhostServer, RedirectUrl = "http://localhost:47336", Token = dropboxPluginConfiguration }; var httpBehaviour = OAuth2HttpBehaviourFactory.Create(_oAuth2Settings); _oAuthHttpBehaviour = httpBehaviour; // Use the default network settings httpBehaviour.HttpSettings = networkConfiguration; }
public OneDriveDestination( IOneDriveConfiguration oneDriveConfiguration, IOneDriveLanguage oneDriveLanguage, INetworkConfiguration networkConfiguration, IResourceProvider resourceProvider, Func <CancellationTokenSource, Owned <PleaseWaitForm> > pleaseWaitFormFactory, ICoreConfiguration coreConfiguration, IGreenshotLanguage greenshotLanguage ) : base(coreConfiguration, greenshotLanguage) { _oneDriveConfiguration = oneDriveConfiguration; _oneDriveLanguage = oneDriveLanguage; _resourceProvider = resourceProvider; _pleaseWaitFormFactory = pleaseWaitFormFactory; // Configure the OAuth2 settings for OneDrive communication _oauth2Settings = new OAuth2Settings { AuthorizationUri = OAuth2Uri.AppendSegments("authorize") .ExtendQuery(new Dictionary <string, string> { { "response_type", "code" }, { "client_id", "{ClientId}" }, { "redirect_uri", "{RedirectUrl}" }, { "state", "{State}" }, { "scope", "files.readwrite offline_access" } }), TokenUrl = OAuth2Uri.AppendSegments("token"), CloudServiceName = "OneDrive", ClientId = _oneDriveConfiguration.ClientId, ClientSecret = "", RedirectUrl = "https://login.microsoftonline.com/common/oauth2/nativeclient", AuthorizeMode = AuthorizeModes.EmbeddedBrowser, Token = oneDriveConfiguration }; _oneDriveHttpBehaviour = new HttpBehaviour { HttpSettings = networkConfiguration, JsonSerializer = new JsonNetJsonSerializer() }; }
/// <summary> /// Do the actual upload to Picasa /// </summary> /// <param name="surfaceToUpload">Image to upload</param> /// <param name="outputSettings"></param> /// <param name="title"></param> /// <param name="filename"></param> /// <returns>PicasaResponse</returns> public static string UploadToPicasa(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename) { // Fill the OAuth2Settings var settings = new OAuth2Settings { AuthUrlPattern = AuthUrl, TokenUrl = TokenUrl, CloudServiceName = "Picasa", ClientId = PicasaCredentials.ClientId, ClientSecret = PicasaCredentials.ClientSecret, AuthorizeMode = OAuth2AuthorizeMode.LocalServer, RefreshToken = Config.RefreshToken, AccessToken = Config.AccessToken, AccessTokenExpires = Config.AccessTokenExpires }; // Copy the settings from the config, which is kept in memory and on the disk try { var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, string.Format(UploadUrl, Config.UploadUser, Config.UploadAlbum), settings); if (Config.AddFilename) { webRequest.Headers.Add("Slug", NetworkHelper.EscapeDataString(filename)); } SurfaceContainer container = new SurfaceContainer(surfaceToUpload, outputSettings, filename); container.Upload(webRequest); string response = NetworkHelper.GetResponseAsString(webRequest); return(ParseResponse(response)); } finally { // Copy the settings back to the config, so they are stored. Config.RefreshToken = settings.RefreshToken; Config.AccessToken = settings.AccessToken; Config.AccessTokenExpires = settings.AccessTokenExpires; Config.IsDirty = true; IniConfig.Save(); } }
public ImgurApi( IImgurConfiguration imgurConfiguration, ICoreConfiguration coreConfiguration, INetworkConfiguration networkConfiguration) { _imgurConfiguration = imgurConfiguration; _coreConfiguration = coreConfiguration; // Configure the OAuth2 settings for Imgur communication _oauth2Settings = new OAuth2Settings { AuthorizationUri = new Uri("https://api.imgur.com").AppendSegments("oauth2", "authorize"). ExtendQuery(new Dictionary <string, string> { { "response_type", "code" }, { "client_id", "{ClientId}" }, { "redirect_uri", "{RedirectUrl}" }, // TODO: Add version? { "state", "{State}" } }), TokenUrl = new Uri("https://api.imgur.com/oauth2/token"), CloudServiceName = "Imgur", ClientId = imgurConfiguration.ClientId, ClientSecret = imgurConfiguration.ClientSecret, RedirectUrl = "https://getgreenshot.org/oauth/imgur", AuthorizeMode = AuthorizeModes.OutOfBoundAuto, Token = imgurConfiguration }; Behaviour = new HttpBehaviour { HttpSettings = networkConfiguration, JsonSerializer = new JsonNetJsonSerializer(), OnHttpClientCreated = httpClient => { httpClient.SetAuthorization("Client-ID", _imgurConfiguration.ClientId); httpClient.DefaultRequestHeaders.ExpectContinue = false; } }; }
public OAuth2Tests(ITestOutputHelper testOutputHelper) { LogSettings.RegisterDefaultLogger <XUnitLogger>(LogLevels.Verbose, testOutputHelper); var oAuth2Settings = new OAuth2Settings { ClientId = "<client id from google developer console>", ClientSecret = "<client secret from google developer console>", CloudServiceName = "Google", AuthorizeMode = AuthorizeModes.LocalhostServer, TokenUrl = GoogleApiUri.AppendSegments("oauth2", "v4", "token"), AuthorizationUri = new Uri("https://accounts.google.com").AppendSegments("o", "oauth2", "v2", "auth") .ExtendQuery(new Dictionary <string, string> { { "response_type", "code" }, { "client_id", "{ClientId}" }, { "redirect_uri", "{RedirectUrl}" }, { "state", "{State}" }, { "scope", GoogleApiUri.AppendSegments("auth", "calendar").AbsoluteUri } }) }; _oAuthHttpBehaviour = OAuth2HttpBehaviourFactory.Create(oAuth2Settings); }
/// <summary> /// Do the actual upload to Picasa /// </summary> /// <param name="oAuth2Settings">OAuth2Settings</param> /// <param name="surfaceToUpload">ICapture</param> /// <param name="otherParameters">IDictionary</param> /// <param name="progress">IProgress</param> /// <param name="token"></param> /// <returns>PicasaResponse</returns> public async Task <ImgurImage> AuthenticatedUploadToImgurAsync(OAuth2Settings oAuth2Settings, ISurface surfaceToUpload, IDictionary <string, string> otherParameters, IProgress <int> progress = null, CancellationToken token = default) { var uploadUri = new Uri(_imgurConfiguration.ApiUrl).AppendSegments("upload.json").ExtendQuery(otherParameters); var localBehaviour = Behaviour.ShallowClone(); if (progress != null) { localBehaviour.UploadProgress = percent => { UiContext.RunOn(() => progress.Report((int)(percent * 100)), token); }; } var oauthHttpBehaviour = OAuth2HttpBehaviourFactory.Create(oAuth2Settings, localBehaviour); using (var imageStream = new MemoryStream()) { surfaceToUpload.WriteToStream(imageStream, _coreConfiguration, _imgurConfiguration); imageStream.Position = 0; using (var content = new StreamContent(imageStream)) { content.Headers.Add("Content-Type", surfaceToUpload.GenerateMimeType(_coreConfiguration, _imgurConfiguration)); oauthHttpBehaviour.MakeCurrent(); return(await uploadUri.PostAsync <ImgurImage>(content, token).ConfigureAwait(false)); } } }
public async Task OAuth2RequestSigningHandler_ClientCredentialsGrant_AuthorisesOk() { #region Test Setup MockMessageHandler mockHandler = SetupOAuth2MockHandler(); var credentials = new SimpleCredentials() { Identifier = "987654321", Secret = "abcdefghilmnopqrstuvzabc" }; var settings = new OAuth2Settings(); //Set the grant type settings.GrantType = OAuth2GrantTypes.ClientCredentials; //Set the credentials to use when requesting a new token settings.ClientCredentialProvider = new SimpleCredentialProvider(credentials); // Make sure token requests use our mock handler settings.CreateHttpClient = () => new System.Net.Http.HttpClient(mockHandler); //These settings are provided for all auth flows settings.AccessTokenUrl = new Uri("http://testsite.com/Token"); settings.AuthorizeUrl = new Uri("http://testsite.com/Authorize"); settings.RedirectUrl = new Uri("http://testsite.com/redirect"); // Create a request signer using the config var signer = new OAuth2RequestSigningHandler(settings, mockHandler); #endregion var client = new System.Net.Http.HttpClient(signer); var result = await client.GetAsync("http://testsite.com/TestEndpoint"); result.EnsureSuccessStatusCode(); }
public GooglePhotosDestination( IGooglePhotosConfiguration googlePhotosConfiguration, IGooglePhotosLanguage googlePhotosLanguage, INetworkConfiguration networkConfiguration, IResourceProvider resourceProvider, ICoreConfiguration coreConfiguration, IGreenshotLanguage greenshotLanguage, Func <CancellationTokenSource, Owned <PleaseWaitForm> > pleaseWaitFormFactory ) : base(coreConfiguration, greenshotLanguage) { _googlePhotosConfiguration = googlePhotosConfiguration; _googlePhotosLanguage = googlePhotosLanguage; _networkConfiguration = networkConfiguration; _resourceProvider = resourceProvider; _pleaseWaitFormFactory = pleaseWaitFormFactory; _oAuth2Settings = new OAuth2Settings { AuthorizationUri = new Uri("https://accounts.google.com").AppendSegments("o", "oauth2", "auth"). ExtendQuery(new Dictionary <string, string> { { "response_type", "code" }, { "client_id", "{ClientId}" }, { "redirect_uri", "{RedirectUrl}" }, { "state", "{State}" }, { "scope", "https://picasaweb.google.com/data/" } }), TokenUrl = new Uri("https://www.googleapis.com/oauth2/v3/token"), CloudServiceName = "GooglePhotos", ClientId = googlePhotosConfiguration.ClientId, ClientSecret = googlePhotosConfiguration.ClientSecret, RedirectUrl = "http://getgreenshot.org", AuthorizeMode = AuthorizeModes.LocalhostServer, Token = googlePhotosConfiguration }; }
public void OAuth2RequestSigningHandler_Constructor_ThrowsOnInvalidSettings() { var settings = new OAuth2Settings(); var handler = new OAuth2RequestSigningHandler(settings); }
public OAuth2Consumer(OAuth2Settings settings) { this.Settings = settings; }
/// <summary> /// Do the actual upload to Imgur /// For more details on the available parameters, see: http://api.imgur.com/resources_anon /// </summary> /// <param name="surfaceToUpload">ISurface to upload</param> /// <param name="outputSettings">OutputSettings for the image file format</param> /// <param name="title">Title</param> /// <param name="filename">Filename</param> /// <returns>ImgurInfo with details</returns> public static ImgurInfo UploadToImgur(ISurface surfaceToUpload, SurfaceOutputSettings outputSettings, string title, string filename) { IDictionary <string, object> otherParameters = new Dictionary <string, object>(); // add title if (title != null && Config.AddTitle) { otherParameters["title"] = title; } // add filename if (filename != null && Config.AddFilename) { otherParameters["name"] = filename; } string responseString = null; if (Config.AnonymousAccess) { // add key, we only use the other parameters for the AnonymousAccess //otherParameters.Add("key", IMGUR_ANONYMOUS_API_KEY); HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(Config.ImgurApi3Url + "/upload.xml?" + NetworkHelper.GenerateQueryParameters(otherParameters), HTTPMethod.POST); webRequest.ContentType = "image/" + outputSettings.Format; webRequest.ServicePoint.Expect100Continue = false; SetClientId(webRequest); try { using (var requestStream = webRequest.GetRequestStream()) { ImageOutput.SaveToStream(surfaceToUpload, requestStream, outputSettings); } using (WebResponse response = webRequest.GetResponse()) { LogRateLimitInfo(response); var responseStream = response.GetResponseStream(); if (responseStream != null) { using (StreamReader reader = new StreamReader(responseStream, true)) { responseString = reader.ReadToEnd(); } } } } catch (Exception ex) { Log.Error("Upload to imgur gave an exeption: ", ex); throw; } } else { var oauth2Settings = new OAuth2Settings { AuthUrlPattern = AuthUrlPattern, TokenUrl = TokenUrl, RedirectUrl = "https://imgur.com", CloudServiceName = "Imgur", ClientId = ImgurCredentials.CONSUMER_KEY, ClientSecret = ImgurCredentials.CONSUMER_SECRET, AuthorizeMode = OAuth2AuthorizeMode.EmbeddedBrowser, BrowserSize = new Size(680, 880), RefreshToken = Config.RefreshToken, AccessToken = Config.AccessToken, AccessTokenExpires = Config.AccessTokenExpires }; // Copy the settings from the config, which is kept in memory and on the disk try { var webRequest = OAuth2Helper.CreateOAuth2WebRequest(HTTPMethod.POST, Config.ImgurApi3Url + "/upload.xml", oauth2Settings); otherParameters["image"] = new SurfaceContainer(surfaceToUpload, outputSettings, filename); NetworkHelper.WriteMultipartFormData(webRequest, otherParameters); responseString = NetworkHelper.GetResponseAsString(webRequest); } finally { // Copy the settings back to the config, so they are stored. Config.RefreshToken = oauth2Settings.RefreshToken; Config.AccessToken = oauth2Settings.AccessToken; Config.AccessTokenExpires = oauth2Settings.AccessTokenExpires; Config.IsDirty = true; IniConfig.Save(); } } if (string.IsNullOrEmpty(responseString)) { return(null); } return(ImgurInfo.ParseResponse(responseString)); }