public void GivenNoCodeAndNoErrorWasReturned_AuthenticateClient_ThrowsAnException() { // Arrange. var linkedinProvider = new LinkedInProvider(new ProviderParams { Key = "aa", Secret = "bb" }); const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "aaa", "bbb" }, { "state", existingState } }; var linkedInAuthenticationServiceSettings = new LinkedInAuthenticationServiceSettings { State = existingState }; // Act. var result = Assert.Throws <AuthenticationException>( () => linkedinProvider.AuthenticateClient(linkedInAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal("No code parameter provided in the response query string from LinkedIn.", result.Message); }
protected void Page_Load(object sender, EventArgs e) { CheckPermissions(ModuleName.SOCIALMARKETING, PermissionsEnum.Read.ToString()); PageTitle.TitleText = GetString("sm.linkedin.account.companyaccesstoken"); PageTitle.ShowFullScreenButton = false; PageTitle.ShowCloseButton = false; if (Parameters == null) { ShowError(GetString("dialogs.badhashtext")); return; } var data = LinkedInProvider.GetLinkedInData(); if (data.UserDeniedAccess) { ShowError(GetString("sm.linkedin.account.msg.accesstokenrefused")); return; } var url = LinkedInHelper.GetPurifiedUrl(); if (!String.IsNullOrEmpty(data.Code)) { CompleteAuthorization(data, url); return; } BeginAuthorization(url); }
public void GivenLinkedInReturnedAnError_AuthenticateClient_ThrowsAnException() { // Arrange. var linkedinProvider = new LinkedInProvider(new ProviderParams { Key = "aa", Secret = "bb" }); const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "error", "I dont' always use bayonets. But when I do, I transport them on Aircraft Carriers." }, { "state", existingState } }; var linkedInAuthenticationServiceSettings = new LinkedInAuthenticationServiceSettings { State = existingState }; // Act. var result = Assert.Throws <AuthenticationException>( () => linkedinProvider.AuthenticateClient(linkedInAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "Failed to retrieve an authorization code from LinkedIn. The error provided is: I dont' always use bayonets. But when I do, I transport them on Aircraft Carriers.", result.Message); }
protected void Page_Load(object sender, EventArgs e) { PageTitle.TitleText = ResHelper.GetString("socialnetworking.linkedin.accesstoken"); PageTitle.ShowFullScreenButton = false; PageTitle.ShowCloseButton = false; string txtToken = QueryHelper.GetString("txtToken", String.Empty); string consumerKey = QueryHelper.GetString("apiKey", String.Empty); string consumerSecret = QueryHelper.GetString("apiSecret", String.Empty); string oauthToken = QueryHelper.GetString("oauth_token", String.Empty); string error = QueryHelper.GetString("oauth_problem", String.Empty); // Check Social networking DLL and settings if (!SystemContext.IsFullTrustLevel) { lblStatus.Text = ResHelper.GetString("socialnetworking.fulltrustrequired"); } else if ((String.IsNullOrEmpty(consumerKey) || String.IsNullOrEmpty(consumerSecret)) && String.IsNullOrEmpty(oauthToken) && String.IsNullOrEmpty(error)) { lblStatus.Text = ResHelper.GetString("socialnetworking.linkedin.apisettingsmissing"); } else { // If access denied if (error.EqualsCSafe("user_refused")) { // Close the window StringBuilder script = new StringBuilder("if(wopener.setAccessTokenToTextBox){ CloseDialog(); }"); ScriptHelper.RegisterStartupScript(Page, typeof(string), "TokenScript", ScriptHelper.GetScript(script.ToString())); } else { try { // Authenticate and retrieve tokens Dictionary <string, string> tokens = LinkedInProvider.Authorize(txtToken); if (tokens.Count != 0) { // Return access token values and close the window StringBuilder script = new StringBuilder("if(wopener.setAccessTokenToTextBox){ wopener.setAccessTokenToTextBox('") .AppendFormat("{0}', '{1}', '{2}'); CloseDialog(); }}", txtToken, tokens["AccessToken"], tokens["AccessTokenSecret"]); ScriptHelper.RegisterStartupScript(Page, typeof(string), "TokenScript", ScriptHelper.GetScript(script.ToString())); } else { // Error occurred while communicating with LinkedIn lblStatus.Text = ResHelper.GetString("socialnetworking.authorizationerror"); } } catch (Exception ex) { LogAndShowError("SocialMedia", "LinkedInProvider", ex); } } } }
public void GivenExecutingUserInfoWorksButIsMissingSomeRequiredData_AuthenticateClient_ThrowsAnException() { // Arrange. var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult { AccessToken = "aaa", ExpiresIn = 10 }); var mockRestResponseUserInfo = new Mock <IRestResponse <UserInfoResult> >(); mockRestResponseUserInfo.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponseUserInfo.Setup(x => x.Data).Returns(new UserInfoResult()); // Missing required info. var mockRestClient = new Mock <IRestClient>(); mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); mockRestClient. Setup(x => x.Execute <UserInfoResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponseUserInfo.Object); mockRestClient.Setup(x => x.BuildUri(It.IsAny <IRestRequest>())) .Returns(new Uri("http://www.windowsazure.com")); var linkedinProvider = new LinkedInProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var linkedInAuthenticationServiceSettings = new LinkedInAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => linkedinProvider.AuthenticateClient(linkedInAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "We were unable to retrieve the User Id from LinkedIn API, the user may have denied the authorization.", result.Message); }
public void GivenExecutingUserInfoThrowsAnException_AuthenticateClient_ThrowsAnException() { // Arrange. var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult { AccessToken = "aaa", ExpiresIn = 10 }); var mockRestResponseUserInfo = new Mock <IRestResponse <UserInfoResult> >(); mockRestResponseUserInfo.Setup(x => x.StatusCode).Returns(HttpStatusCode.Unauthorized); mockRestResponseUserInfo.Setup(x => x.StatusDescription).Returns("Unauthorized"); var mockRestClient = new Mock <IRestClient>(); mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); mockRestClient. Setup(x => x.Execute <UserInfoResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponseUserInfo.Object); mockRestClient.Setup(x => x.BuildUri(It.IsAny <IRestRequest>())) .Returns(new Uri("http://www.windowsazure.com")); var linkedinProvider = new LinkedInProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var linkedInAuthenticationServiceSettings = new LinkedInAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => linkedinProvider.AuthenticateClient(linkedInAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "Failed to obtain some UserInfo data from the LinkedIn Api OR the the response was not an HTTP Status 200 OK. Response Status: Unauthorized. Response Description: Unauthorized. Error Message: --no error exception--.", result.Message); }
protected void Page_Load(object sender, EventArgs e) { CurrentMaster.Title.TitleText = ResHelper.GetString("socialnetworking.linkedin.accesstoken"); CurrentMaster.Title.TitleImage = GetImageUrl("Others/LinkedIn/linkedin.png"); string txtToken = QueryHelper.GetString("txtToken", String.Empty); string consumerKey = QueryHelper.GetString("apiKey", String.Empty); string consumerSecret = QueryHelper.GetString("apiSecret", String.Empty); string oauthToken = QueryHelper.GetString("oauth_token", String.Empty); string error = QueryHelper.GetString("oauth_problem", String.Empty); Dictionary <string, string> tokens = null; // Check Social networking DLL and settings if (!SiteManagerFunctions.CheckSocialNetworkingDLL()) { lblStatus.Text = ResHelper.GetString("socialnetworking.renameddll"); } else if ((String.IsNullOrEmpty(consumerKey) || String.IsNullOrEmpty(consumerSecret)) && String.IsNullOrEmpty(oauthToken) && String.IsNullOrEmpty(error)) { lblStatus.Text = ResHelper.GetString("socialnetworking.linkedin.apisettingsmissing"); } else { // If access denied if (error.EqualsCSafe("user_refused")) { // Close the window StringBuilder script = new StringBuilder("if(wopener.setAccessTokenToTextBox){ CloseDialog(); }"); ScriptHelper.RegisterStartupScript(Page, typeof(string), "TokenScript", ScriptHelper.GetScript(script.ToString())); } else { // Authenticate and retrieve tokens tokens = LinkedInProvider.Authorize(txtToken); if (tokens.Count != 0) { // Return access token values and close the window StringBuilder script = new StringBuilder("if(wopener.setAccessTokenToTextBox){ wopener.setAccessTokenToTextBox('") .AppendFormat("{0}', '{1}', '{2}'); CloseDialog(); }}", txtToken, tokens["AccessToken"], tokens["AccessTokenSecret"]); ScriptHelper.RegisterStartupScript(Page, typeof(string), "TokenScript", ScriptHelper.GetScript(script.ToString())); } else { // Error occured while communicating with LinkedIn lblStatus.Text = ResHelper.GetString("socialnetworking.authorizationerror"); } } } }
protected void Page_Load(object sender, EventArgs e) { PageTitle.TitleText = GetString("socialnetworking.linkedin.accesstoken"); PageTitle.ShowFullScreenButton = false; PageTitle.ShowCloseButton = false; var data = LinkedInProvider.GetLinkedInData(); if (data.SettingsMissing) { lblStatus.Text = GetString("socialnetworking.linkedin.apisettingsmissing"); return; } var returnUrl = new Uri(URLHelper.GetAbsoluteUrl(LinkedInProvider.ACCESS_TOKEN_PAGE)); // User allowed access if (!String.IsNullOrEmpty(data.Code)) { // Authenticate and retrieve tokens if (LinkedInProvider.Authorize(data, returnUrl, out var token)) { // Return access token values and close the window var script = new StringBuilder("if(wopener.setAccessTokenToTextBox){ wopener.setAccessTokenToTextBox('") .AppendFormat("{0}', '{1}'); CloseDialog(); }}", data.EditorId, token.AccessToken); ScriptHelper.RegisterStartupScript(Page, typeof(string), "TokenScript", ScriptHelper.GetScript(script.ToString())); } else { // Error occurred while communicating with LinkedIn lblStatus.Text = GetString("socialnetworking.authorizationerror"); } return; } // User denied access if (data.UserDeniedAccess) { // Close the window var script = new StringBuilder("if(wopener.setAccessTokenToTextBox){ CloseDialog(); }"); ScriptHelper.RegisterStartupScript(Page, typeof(string), "TokenScript", ScriptHelper.GetScript(script.ToString())); return; } LinkedInProvider.OpenAuthorizationPage(data, returnUrl); }
/// <summary> /// Begins authorization process and redirects client to the LinkedIn authorization page. /// </summary> private void BeginAuthorization(Uri url) { try { var data = new LinkedInData((string)Parameters["ApiKey"], (string)Parameters["ApiSecret"]); LinkedInProvider.OpenAuthorizationPage(data, url); } catch (CMS.SocialMarketing.LinkedInApiUnauthorizedException) { // The keys in LinkedIn application are not valid ShowError(GetString("sm.linkedin.account.msg.unauthorized")); } catch (Exception ex) { LogAndShowError("LinkedInCompanyAccessToken", "AUTH_BEGIN", ex); } }
public void GivenANullCallbackUriWhileTryingToRetrieveAnAccessToken_AuthenticateClient_ThrowsAnException() { // Arrange. var mockRestClient = new Mock <IRestClient>(); var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.BadRequest); mockRestResponse.Setup(x => x.StatusDescription).Returns("Bad Request"); mockRestResponse.Setup(x => x.Content).Returns("{\n \"error\" : \"invalid_request\"\n}"); mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); mockRestClient.Setup(x => x.BuildUri(It.IsAny <IRestRequest>())) .Returns(new Uri("http://www.windowsazure.com")); var linkedinProvider = new LinkedInProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var linkedInAuthenticationServiceSettings = new LinkedInAuthenticationServiceSettings { CallBackUri = new Uri("http://2p1s.com"), State = existingState }; // Act. var result = Assert.Throws <AuthenticationException>( () => linkedinProvider.AuthenticateClient(linkedInAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "Failed to obtain an Access Token from LinkedIn OR the the response was not an HTTP Status 200 OK. Response Status: BadRequest. Response Description: Bad Request. Error Content: {\n \"error\" : \"invalid_request\"\n}. Error Message: --no error exception--.", result.Message); }
/// <summary> /// Completes the authorization process. Access tokens and list of administrated companies are retrived and set to control that opened the dialog. /// </summary> private void CompleteAuthorization(ILinkedInData data, Uri url) { if (LinkedInProvider.Authorize(data, url, out var token)) { List <CMS.SocialMarketing.LinkedInCompany> companies; try { companies = CMS.SocialMarketing.LinkedInHelper.GetUserCompanies(token.AccessToken); } catch (Exception ex) { LogAndShowError("LinkedInCompanyAccessToken", "GET_COMPANIES", ex); return; } string formattedExpiration = token.Expiration.HasValue ? TimeZoneHelper.ConvertToUserTimeZone(token.Expiration.Value, true, MembershipContext.AuthenticatedUser, SiteContext.CurrentSite) : String.Empty; string json = JsonConvert.SerializeObject( new { accessToken = token.AccessToken, accessTokenSecret = "", tokenExpiration = token.Expiration.HasValue ? token.Expiration.Value.ToString("g", CultureInfo.InvariantCulture) : String.Empty, tokenExpirationString = formattedExpiration, tokenAppId = Parameters["AppInfoId"], companies }, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml } ); // Set retrieved access token to the opener window string script = String.Format(@" if(wopener.linkedInCompanyControl && wopener.linkedInCompanyControl['{0}']) {{ wopener.linkedInCompanyControl['{0}'].setData({1}); }} CloseDialog();", Parameters["ClientID"], json); ScriptHelper.RegisterStartupScript(Page, typeof(string), "TokenScript", script, true); } }
public void GivenAnRequestTokenWithMissingParameters_AuthenticateClient_ThrowsAnException() { // Arrange. var mockRestClient = new Mock <IRestClient>(); var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult()); mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); mockRestClient.Setup(x => x.BuildUri(It.IsAny <IRestRequest>())) .Returns(new Uri("http://www.windowsazure.com")); var linkedinProvider = new LinkedInProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var linkedInAuthenticationServiceSettings = new LinkedInAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => linkedinProvider.AuthenticateClient(linkedInAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "Retrieved a LinkedIn Access Token but it doesn't contain one or more of either: oauth2_access_token or expires_in.", result.Message); }
public void GivenAnErrorOccuredWhileTryingToRetrieveAnAccessToken_AuthenticateClient_ThrowsAnException() { // Arrange. var mockRestClient = new Mock <IRestClient>(); const string errorMessage = "If God says he was not created by a creator, does that mean: god is an aetheist?"; mockRestClient.Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Throws(new InvalidOperationException(errorMessage)); mockRestClient.Setup(x => x.BuildUri(It.IsAny <IRestRequest>())) .Returns(new Uri("http://www.windowsazure.com")); var linkedinProvider = new LinkedInProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var linkedInAuthenticationServiceSettings = new LinkedInAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => linkedinProvider.AuthenticateClient(linkedInAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "Failed to retrieve an Access Token from LinkedIn.", result.Message); Assert.NotNull(result.InnerException); Assert.Equal(errorMessage, result.InnerException.Message); }
public void GivenAnInvalidRequestToken_AuthenticateClient_ThrowsAnException() { // Arrange. var mockRestClient = new Mock <IRestClient>(); var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.Unauthorized); mockRestResponse.Setup(x => x.StatusDescription).Returns("Unauthorized"); mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); var linkedinProvider = new LinkedInProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var linkedInAuthenticationServiceSettings = new LinkedInAuthenticationServiceSettings { CallBackUri = new Uri("http://2p1s.com"), State = existingState }; // Act. var result = Assert.Throws <AuthenticationException>( () => linkedinProvider.AuthenticateClient(linkedInAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "Failed to obtain an Access Token from LinkedIn OR the the response was not an HTTP Status 200 OK. Response Status: Unauthorized. Response Description: Unauthorized", result.Message); }
public void GivenSomeState_RedirectToAuthenticate_ReturnsAUri() { // Arrange. var linkedinProvider = new LinkedInProvider(new ProviderParams { Key = "aa", Secret = "bb" }); // Act. var result = linkedinProvider.RedirectToAuthenticate(new LinkedInAuthenticationServiceSettings { CallBackUri = new Uri("http://wwww.pewpew.com/"), State = "bleh" }); // Assert. Assert.NotNull(result); Assert.Equal( "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=aa&redirect_uri=http://wwww.pewpew.com/&scope=r_basicprofile%20r_emailaddress&state=bleh", result.AbsoluteUri); }
public void GivenExecutingRetrieveSomeUserInfo_AuthenticateClient_ReturnsAnAuthenticatedClient() { // Arrange. const string accessToken = "aaa"; var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); var accessTokenResult = new AccessTokenResult { AccessToken = accessToken, ExpiresIn = 10 }; mockRestResponse.Setup(x => x.Data).Returns(accessTokenResult); var userInfoResult = new UserInfoResult { EmailAddress = "asdasdas", Id = "1", FirstName = "AAAA", LastName = "bbbbbb" }; var mockRestResponseUserInfo = new Mock <IRestResponse <UserInfoResult> >(); mockRestResponseUserInfo.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponseUserInfo.Setup(x => x.Data).Returns(userInfoResult); var mockRestClient = new Mock <IRestClient>(); mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); mockRestClient. Setup(x => x.Execute <UserInfoResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponseUserInfo.Object); mockRestClient.Setup(x => x.BuildUri(It.IsAny <IRestRequest>())) .Returns(new Uri("http://www.windowsazure.com")); var linkedinProvider = new LinkedInProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", accessToken }, { "state", existingState } }; var linkedInAuthenticationServiceSettings = new LinkedInAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = linkedinProvider.AuthenticateClient(linkedInAuthenticationServiceSettings, queryStringParameters); // Assert. Assert.NotNull(result); Assert.Equal("linkedin", result.ProviderName); Assert.NotNull(result.AccessToken); Assert.Equal(accessToken, result.AccessToken.PublicToken); Assert.True(DateTime.UtcNow <= result.AccessToken.ExpiresOn); Assert.NotNull(result.UserInformation); Assert.Equal(GenderType.Unknown, result.UserInformation.Gender); Assert.Equal(userInfoResult.Id, result.UserInformation.Id); Assert.Equal(userInfoResult.FirstName + " " + userInfoResult.LastName, result.UserInformation.Name); }