(Silverlight) SignalR connection.Start() throws SecurityException - silverlight-5.0

I retrieved Merge branch 'Release 1.1' of SignalR from github. In there are samples for ASP.NET and Silverlight, etc. When I run the ASP.NET sample it works. When I run the Silverlight sample, the connection.Start() throws a SecurityException.
I'm running IE10, Silverlight 5 and .NET 4.5.
In the Silverlight sample, see
MainPage.xaml.cs
var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
connection.Start().ContinueWith(task => **// SecurityException here!**
{
var ex = task.Exception.InnerExceptions[0];
App.ViewModel.Items.Add(ex.Message);
},
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted,
scheduler);

Related

ASP.NET Identity Cookie across subdomains on .Net and Core

I have many application which is hosted on main domain and sub domains:
Website A, ASP.NET (.Net Core 2.0) at www.example.com
Website B, ASP.NET MVC (4.7 .net Framework) at site.example.com
Website C, ASP.NET Identity (.Net Core 2.0) at account.example.com
Website D, ASP.NET Webform (4.7 .net Framework) at file.example.com
I would like to login uses on account.example.com, after authenticate users will redirected to other websites. They will be authorize by there roles on other websites.
I'm trying to share a cookie between these websites and all of the website are hosted on Azure Web App.
I am using ASP.NET Identity (.Net Core 2.0). I'm using the built-in cookie authentication.
How can I use Data Protection in all application and share cookie among them.
For Data Protection my code is:
services.AddDataProtection()
.SetApplicationName("example")
.PersistKeysToFileSystem(new DirectoryInfo(#"%HOME%\ASP.NET\DataProtection-Keys"))
.SetDefaultKeyLifetime(TimeSpan.FromDays(14));
For Cookie Authentication my code is:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
CookieDomain = ".example.com"
});
I got solution from this Microsoft documentation
Share cookies among apps with ASP.NET and ASP.NET Core
And Sample code for this sub-domain authentication system
Cookie Sharing Sample App - GitHub
The sample illustrates cookie sharing across three apps that use cookie authentication:
ASP.NET Core 2.0 Razor Pages app without using ASP.NET Core Identity
ASP.NET Core 2.0 MVC app with ASP.NET Core Identity
ASP.NET Framework 4.6.1 MVC app with ASP.NET Identity
Put this code in your ConfigureServices method in Startup.cs
services.AddDataProtection()
.PersistKeysToFileSystem(GetKeyRingDirInfo())
.SetApplicationName("example");
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "example";
options.Cookie.Domain = ".example.com";
});
For KeyRing method
private DirectoryInfo GetKeyRingDirInfo()
{
var startupAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var applicationBasePath = System.AppContext.BaseDirectory;
var directoryInfo = new DirectoryInfo(applicationBasePath);
do
{
directoryInfo = directoryInfo.Parent;
var keyRingDirectoryInfo = new DirectoryInfo(Path.Combine(directoryInfo.FullName, "KeyRing"));
if (keyRingDirectoryInfo.Exists)
{
return keyRingDirectoryInfo;
}
}
while (directoryInfo.Parent != null);
throw new Exception($"KeyRing folder could not be located using the application root {applicationBasePath}.");
}
Note : You have to copy KeyRing file which is automatically generated on Identity application hosting server and manually paste to other sub-domain and main domain hosting server of other website to share cookie for authentication.
Regarding .Net Core, if you want to share your cookie among several sites, you may try the following to initialize it instead of UseCookieAuthentication:
services.AddAuthentication();
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Lax;
options.Cookie.Name = "CookieName";
//options.Cookie.Domain = ".localhost";
if (!CurrentEnvironment.IsDevelopment())
options.Cookie.Domain = CommonConfig.CookieDomain; // ".mydomain.com"
options.Cookie.HttpOnly = false;
options.Cookie.Expiration = TimeSpan.FromDays(5 * 30);
options.SlidingExpiration = true;
options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
options.LoginPath = new PathString("/Account/Login");
options.LogoutPath = new PathString("/Account/Logoff");
options.AccessDeniedPath = new PathString("/Account/Login");
var protectionProvider = DataProtectionProvider.Create(new DirectoryInfo(CommonConfig.PersistKeysStoreC));
options.DataProtectionProvider = protectionProvider;
// This adds claims data to the cookie...
options.Events.OnSignedIn = async (context) =>
{
System.Security.Claims.ClaimsIdentity identity = (System.Security.Claims.ClaimsIdentity)context.Principal.Identity;
UserManager<AppUser> userManager = context.HttpContext.RequestServices.GetService<UserManager<AppUser>>();
AppUser user = await userManager.GetUserAsync(context.Principal);
identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier, user.Id.ToString()));
//identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Email, user.Email.ToString()));
//identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, user.LastName));
//identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.GivenName, user.FirstName));
};
});
Of course you will need to give the same ProtectionProvider path for all sites.

How to get Selenium running in AWS Lambda using .net core

Trying to get an AWS Lambda function to run Selenium on .NET Core. Here is code:
public string FunctionHandler(ILambdaContext context)
{
context.Logger.LogLine("Entering function");
try
{
var driver = new InternetExplorerDriver();
context.Logger.LogLine("Navigating to URL");
driver.Navigate().GoToUrl("http://www.google.com/");
context.Logger.LogLine("Returning Done");
return "Done";
}
catch (Exception e)
{
context.Logger.LogLine("Oops: " + e);
return "Failed";
}
}
The error I get in the AWS console is:
OpenQA.Selenium.WebDriverException: Cannot start the driver service on http://localhost:41663/
at OpenQA.Selenium.DriverService.Start()
at OpenQA.Selenium.Remote.DriverServiceCommandExecutor.Execute(Command commandToExecute)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
at OpenQA.Selenium.IE.InternetExplorerDriver..ctor(InternetExplorerDriverService service, InternetExplorerOptions options, TimeSpan commandTimeout)
at OpenQA.Selenium.IE.InternetExplorerDriver..ctor(InternetExplorerDriverService service, InternetExplorerOptions options)
at OpenQA.Selenium.IE.InternetExplorerDriver..ctor(InternetExplorerOptions options)
at OpenQA.Selenium.IE.InternetExplorerDriver..ctor()
at InstagramMagic.Function.FunctionHandler(ILambdaContext context)
It is possible, but so far I've only had luck getting it to work with Chrome. AWS Lambda is running a bare bones version of Amazon Linux. If you want to run something on it beyond the basics, you must package a zip file and deploy it with all of the binaries required. Unfortunately, I doubt IE will run on AWS Lambda. However, there is hope it could run on Azure's equivalent service, which uses what they call a 'Windows Container'.
You have to specify where the Chrome binary is located within Lambda's runtime file system that contains your function, which is going to be /var/task/. This is a node.js example of what you are attempting to do, but using chromedriver.
'use strict';
exports.handler = (event, context, callback) => {
var webdriver = require('selenium-webdriver');
var chrome = require('selenium-webdriver/chrome');
var builder = new webdriver.Builder().forBrowser('chrome');
var chromeOptions = new chrome.Options();
const defaultChromeFlags = [
'--headless',
'--disable-gpu',
'--window-size=1280x1696', // Letter size
'--no-sandbox',
'--user-data-dir=/tmp/user-data',
'--hide-scrollbars',
'--enable-logging',
'--log-level=0',
'--v=99',
'--single-process',
'--data-path=/tmp/data-path',
'--ignore-certificate-errors',
'--homedir=/tmp',
'--disk-cache-dir=/tmp/cache-dir'
];
chromeOptions.setChromeBinaryPath("/var/task/lib/chrome");
chromeOptions.addArguments(defaultChromeFlags);
builder.setChromeOptions(chromeOptions);
var driver = builder.build();
driver.get(event.url);
driver.getTitle().then(function(title) {
console.log("Page title for " + event.url + " is " + title)
callback(null, 'Page title for ' + event.url + ' is ' + title);
});
driver.quit();
};
I actually have a runnable packaged zip of this with a video tutorial on github, with a more detailed explanation. Peak inside the zip file to get an idea how the package should be laid out. https://blackboard.github.io/lambda-selenium/
In addition, I've submitted an issue on your behalf for a runnable .net core example.
https://github.com/blackboard/lambda-selenium/issues/22

Sharepoint testing in Pester

I am currently working on some PowerShell script for SharePoint farm configuration (for example a script for SPWebapplication creation, User profile service application creation, MMS service application creation or search service application creation). My requirement is to test this module using Pester framework. I have very basic understanding about Pester. A sample code for web app creation is below:
$webApplicationName = "A Name"
$hostingMainURL = "http://.....local"
$ContentDatabase = "Datacom_WebApp_ContentDB"
$applicationPoolDisplayName = "TestApppool"
$applicationPoolIdentity = (Get-SPManagedAccount "DEV\Apppool accountName")
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$ap = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication
$applicationPoolDisplayName -ApplicationPoolAccount $applicationPoolIdentity -
Port 80 -AuthenticationProvider $ap -DatabaseName $ContentDatabase
Write-Host "Set content database limits settings for $ContentDatabase..." -Foreground "green"
Set-SPContentDatabase -Identity $ContentDatabase -MaxSiteCount 1 -WarningSiteCount 0
New-SPSite -Url $hostingMainURL -owneralias $username -Name $webApplicationName -Description "Hosting root site collection"
I need a starting point from here. I need some advise on how I can create some test cases on Mocking for example:
Mock New-SPWebapplication
Mock Get-SPManagedAccount
Mock New-SPSite
inModuleScope 'ModuleCallingSpWeb' {
function Get-SPWebApplication {}
Mock -ModuleName ModuleCallingSpWeb Get-SPWebApplication
}

Ember integration test error

Based on this excellent screencast and example, I've been able to unit test my Ember (RC7) app successfully, writing to model objects and such. I'm having trouble with integration testing. I even tried the most basic sort of test, as seen below, but to no avail. Any tips on what I'm doing wrong?
I'm getting this error from the console:
LOG: 'App ready'
INFO: 'generated -> route:application', Object{fullName: 'route:application'}
LOG: 'NeedsAuthMixin: user not authenticated (1).'
INFO: 'Rendering application with ', Object{fullName: 'view:application'}
INFO: 'Rendering login with ', Object{fullName: 'view:login'}
LOG: 'Transitioned into 'login''
LOG: 'testing... login screen loads OK 1'
LOG: 'Transitioned into 'login''
Chrome 28.0.1500 (Mac OS X 10.6.8) Integration Tests - load login page FAILED
Expected 1 assertions, but 0 were run
Background: As you can see, as my app loads, it checks for user authentication, whereupon it transitions to a login page if user isn't authenticated.
This is the code that calls the test (generated from coffeescript):
asyncTest("test: load login page", function() {
expect(1);
console.log("testing... login screen loads OK 1");
return visit("/login").then(function() {
return ok(1 === 1, "Value equal 1.");
});
});
My Karma config file is here.
Bryan
I think it will work if you use test() instead of asyncTest()

REST services - testing PUT methods in the browser

I've developed REST services. I can test the GET methods by the browser, or by a Client Application. But those who have PUT methods I don't know how to consume them by the browser...
For example, I have this method that turns a lamp on, after I insert the userId:
#PUT
#Path("/lampon")
#Produces({"application/json", "text/plain"})
#Consumes("multipart/form-data")
public boolean turnOnLamp(#FormParam("userId") String userId) throws Exception
{
boolean response = new LampManager().turnOnLamp(userId);
return response;
}
In my client application I do this, and it works:
String webPage = "http://localhost:8080/BliveServices/webresources/services.actuators/lampon";
URL urlToRequest = new URL(webPage);
//Authentication
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("Authorization", basicAuth);
urlConnection.setRequestProperty("Content-type", "multipart/form-data");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", "2"));
(...)
But how can I send the userId by the browser?
Another thing, I get this message when I build my project:
SEVERE: Resource methods utilizing #FormParam and consuming "multipart/form-data" are no longer supported. See #FormDataParam.
Thanks
If you want to test the REST-Webservice with your Browser you must install an plugin.
If you use Google Chrome you can install REST Console I also use these plugin to test my Webservice.
https://chrome.google.com/webstore/detail/rest-console/cokgbflfommojglbmbpenpphppikmonn
For Firefox install these REST-Client
https://addons.mozilla.org/en-us/firefox/addon/restclient/
REST CLient is also available for Safari
http://restclient.net/
For Opera you can check out the Simple REST-Client
https://addons.opera.com/en/extensions/details/simple-rest-client/
For your second Question
please try as Consumes value 'application/x-www-form-urlencoded'
To issue a put-request from a browser you could use jQuery's jQuery.ajax(). (http://api.jquery.com/jQuery.ajax/)
For example:
$.ajax({
url: "test-url",
type: "PUT",
data: {userid: 1}
})
Would send a put-request to test-url with the specified data.