Here are the examples of the csharp api Xunit.Assert.Equal(string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
587 Examples
19
View Source File : AzureADAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void AddAzureADBearer_ThrowsWhenBearerSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADBearer(o => { })
.AddAzureADBearer("Custom", AzureADDefaults.JwtBearerAuthenticationScheme, o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
var expectedMessage = $"The JSON Web Token Bearer scheme 'AzureADJwtBearer' can't be replacedociated with the Azure Active Directory scheme 'Custom'. " +
"The JSON Web Token Bearer scheme 'AzureADJwtBearer' is already mapped to the Azure Active Directory scheme 'AzureADBearer'";
// Act & replacedert
var exception = replacedert.Throws<InvalidOperationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
replacedert.Equal(expectedMessage, exception.Message);
}
19
View Source File : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void AddAzureADB2C_ThrowsForDuplicatedSchemes()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADB2C(o => { })
.AddAzureADB2C(o => { });
var provider = services.BuildServiceProvider();
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
// Act & replacedert
var exception = replacedert.Throws<InvalidOperationException>(
() => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));
replacedert.Equal("A scheme with the name 'AzureADB2C' was already added.", exception.Message);
}
19
View Source File : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void AddAzureADB2C_ThrowsWhenOpenIdSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADB2C(o => { })
.AddAzureADB2C("Custom", AzureADB2CDefaults.OpenIdScheme, "Cookie", null, o => { });
var provider = services.BuildServiceProvider();
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
var expectedMessage = $"The Open ID Connect scheme 'AzureADB2COpenID' can't be replacedociated with the Azure Active Directory B2C scheme 'Custom'. " +
"The Open ID Connect scheme 'AzureADB2COpenID' is already mapped to the Azure Active Directory B2C scheme 'AzureADB2C'";
// Act & replacedert
var exception = replacedert.Throws<InvalidOperationException>(
() => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));
replacedert.Equal(expectedMessage, exception.Message);
}
19
View Source File : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void AddAzureADB2C_ThrowsWhenCookieSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADB2C(o => { })
.AddAzureADB2C("Custom", "OpenID", AzureADB2CDefaults.CookieScheme, null, o => { });
var provider = services.BuildServiceProvider();
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
var expectedMessage = $"The cookie scheme 'AzureADB2CCookie' can't be replacedociated with the Azure Active Directory B2C scheme 'Custom'. " +
"The cookie scheme 'AzureADB2CCookie' is already mapped to the Azure Active Directory B2C scheme 'AzureADB2C'";
// Act & replacedert
var exception = replacedert.Throws<InvalidOperationException>(
() => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));
replacedert.Equal(expectedMessage, exception.Message);
}
19
View Source File : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void AddAzureADB2CBearer_ThrowsForDuplicatedSchemes()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADB2CBearer(o => { })
.AddAzureADB2CBearer(o => { });
var provider = services.BuildServiceProvider();
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
// Act & replacedert
var exception = replacedert.Throws<InvalidOperationException>(
() => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));
replacedert.Equal("A scheme with the name 'AzureADB2CBearer' was already added.", exception.Message);
}
19
View Source File : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void AddAzureADB2CBearer_ThrowsWhenBearerSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADB2CBearer(o => { })
.AddAzureADB2CBearer("Custom", AzureADB2CDefaults.JwtBearerAuthenticationScheme, o => { });
var provider = services.BuildServiceProvider();
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
var expectedMessage = $"The JSON Web Token Bearer scheme 'AzureADB2CJwtBearer' can't be replacedociated with the Azure Active Directory B2C scheme 'Custom'. " +
"The JSON Web Token Bearer scheme 'AzureADB2CJwtBearer' is already mapped to the Azure Active Directory B2C scheme 'AzureADB2CBearer'";
// Act & replacedert
var exception = replacedert.Throws<InvalidOperationException>(
() => azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme));
replacedert.Equal(expectedMessage, exception.Message);
}
19
View Source File : AzureADAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void AddAzureAD_ThrowsForDuplicatedSchemes()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureAD(o => { })
.AddAzureAD(o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
// Act & replacedert
var exception = replacedert.Throws<InvalidOperationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
replacedert.Equal("A scheme with the name 'AzureAD' was already added.", exception.Message);
}
19
View Source File : AzureADAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void AddAzureAD_ThrowsWhenOpenIdSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureAD(o => { })
.AddAzureAD("Custom", AzureADDefaults.OpenIdScheme, "Cookie", null, o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
var expectedMessage = $"The Open ID Connect scheme 'AzureADOpenID' can't be replacedociated with the Azure Active Directory scheme 'Custom'. " +
"The Open ID Connect scheme 'AzureADOpenID' is already mapped to the Azure Active Directory scheme 'AzureAD'";
// Act & replacedert
var exception = replacedert.Throws<InvalidOperationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
replacedert.Equal(expectedMessage, exception.Message);
}
19
View Source File : AzureADAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void AddAzureAD_ThrowsWhenCookieSchemeIsAlreadyInUse()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureAD(o => { })
.AddAzureAD("Custom", "OpenID", AzureADDefaults.CookieScheme, null, o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
var expectedMessage = $"The cookie scheme 'AzureADCookie' can't be replacedociated with the Azure Active Directory scheme 'Custom'. " +
"The cookie scheme 'AzureADCookie' is already mapped to the Azure Active Directory scheme 'AzureAD'";
// Act & replacedert
var exception = replacedert.Throws<InvalidOperationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
replacedert.Equal(expectedMessage, exception.Message);
}
19
View Source File : AzureADAuthenticationBuilderExtensionsTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void AddAzureADBearer_ThrowsForDuplicatedSchemes()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
services.AddAuthentication()
.AddAzureADBearer(o => { })
.AddAzureADBearer(o => { });
var provider = services.BuildServiceProvider();
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
// Act & replacedert
var exception = replacedert.Throws<InvalidOperationException>(
() => azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme));
replacedert.Equal("A scheme with the name 'AzureADBearer' was already added.", exception.Message);
}
19
View Source File : DiscoveryTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory, Trait("FunctionalTests", "General")]
[InlineData(HostType.IIS)]
[InlineData(HostType.HttpListener)]
public void DefaultDiscoveryTest(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
string applicationUrl = deployer.Deploy(hostType);
string responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl);
replacedert.Equal(Startup.RESULT, responseText);
}
}
19
View Source File : OwinHostAppSettings.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory, Trait("FunctionalTests", "General")]
[InlineData("FriendlyClreplacedName", "SUCCESS")]
[InlineData("FriendlyClreplacedNameWithMethodNameOverride", "CopyOfConfiguration")]
[InlineData("CustomStartupAttribute", "SUCCESS")]
//Test the case sensitivity of friendly names
[InlineData("friendlyclreplacedname", "SUCCESS")]
public void FriendlyStartupNames(string friendlyAppStartupName, string expectedResponse)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
var applicationUrl = deployer.Deploy(HostType.IIS, Configuration);
var vDirPath = Path.GetDirectoryName(deployer.GetWebConfigPath());
var options = new MyStartOptions(true) { TargetApplicationDirectory = vDirPath, FriendlyAppStartupName = friendlyAppStartupName };
using (new HostServer(options))
{
string response = HttpClientUtility.GetResponseTextFromUrl("http://localhost:5000/");
replacedert.Equal(expectedResponse, response);
}
}
}
19
View Source File : AuthServerTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory, Trait("FunctionalTests", "Security")]
[InlineData(HostType.IIS)]
[InlineData(HostType.HttpListener)]
public void Security_AuthorizeEndpointTests(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
var applicationUrl = deployer.Deploy(hostType, AuthServerHappyPathConfiguration);
IDisposable clientEndpoint = null;
try
{
clientEndpoint = WebApp.Start(Client_Redirect_Uri, app => app.Run(context => { return context.Response.WriteAsync(context.Request.QueryString.Value); }));
string tokenEndpointUri = applicationUrl + "TokenEndpoint";
var basicClient = new HttpClient();
var headerValue = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", "123", "invalid")));
basicClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", headerValue);
HttpClient httpClient = new HttpClient();
string requestUri = null;
Uri landingUri = null;
Uri applicationUri = new Uri(applicationUrl);
HttpResponseMessage httpResponseMessage = null;
//Happy path - response_type:code
requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "validstate");
landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
replacedert.Equal<string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
replacedert.NotNull(landingUri.ParseQueryString()["code"]);
replacedert.Equal<string>("validstate", landingUri.ParseQueryString()["state"]);
//Happy path - response_type:token
requestUri = AuthZ.CreateAuthZUri(applicationUrl, "token", "123", Client_Redirect_Uri, "scope1", "validstate");
landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
landingUri = new Uri(landingUri.AbsoluteUri.Replace('#', '?'));
replacedert.Equal<string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
replacedert.NotNull(landingUri.ParseQueryString()["access_token"]);
replacedert.NotNull(landingUri.ParseQueryString()["expires_in"]);
replacedert.Equal<string>("bearer", landingUri.ParseQueryString()["token_type"]);
replacedert.Equal<string>("validstate", landingUri.ParseQueryString()["state"]);
//Invalid redirect URI - preplaced error to application
requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", "invalid_uri_preplacedonerror", "scope1", "validstate");
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
replacedert.Equal<string>("error: invalid_request\r\n", httpResponseMessage.Content.ReadreplacedtringAsync().Result);
replacedert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
//Invalid redirect URI - Display error by middleware
requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", "invalid_uri_displayerror", "scope1", "validstate");
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
replacedert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
replacedert.True(httpResponseMessage.Content.ReadreplacedtringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");
//What happens if we don't set Validated explicitly. Send an invalid clientId => We don't set Validated for this case.
requestUri = AuthZ.CreateAuthZUri(applicationUrl, "token", "invalidClient", Client_Redirect_Uri, "scope1", "validstate");
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
replacedert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
replacedert.True(httpResponseMessage.Content.ReadreplacedtringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");
//OnValidateAuthorizeRequest - Rejecting a request. Send an invalid state as we validate it there. Client should receive all the error code & description that we send
requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "invalidstate");
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
landingUri = httpResponseMessage.RequestMessage.RequestUri;
replacedert.Equal<string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
replacedert.Equal<string>("state.invalid", landingUri.ParseQueryString()["error"]);
replacedert.Equal<string>("state.invaliddescription", landingUri.ParseQueryString()["error_description"]);
replacedert.Equal<string>("state.invaliduri", landingUri.ParseQueryString()["error_uri"]);
replacedert.True(httpResponseMessage.Content.ReadreplacedtringAsync().Result.StartsWith("error=state.invalid&error_description=state.invaliddescription&error_uri=state.invaliduri"), "Did not receive an error when provider did not set Validated");
//Missing response_type
requestUri = AuthZ.CreateAuthZUri(applicationUrl, null, "123", Client_Redirect_Uri, "scope1", "validstate");
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
replacedert.Equal<string>(Client_Redirect_Uri, httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Path));
replacedert.Equal<string>("invalid_request", httpResponseMessage.RequestMessage.RequestUri.ParseQueryString()["error"]);
//Unsupported response_type
requestUri = AuthZ.CreateAuthZUri(applicationUrl, "invalid_response_type", "123", Client_Redirect_Uri, "scope1", "validstate");
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
replacedert.Equal<string>(Client_Redirect_Uri, httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Path));
replacedert.Equal<string>("unsupported_response_type", httpResponseMessage.RequestMessage.RequestUri.ParseQueryString()["error"]);
//Missing client_id
requestUri = AuthZ.CreateAuthZUri(applicationUrl, "token", null, Client_Redirect_Uri, "scope1", "validstate");
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
replacedert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
replacedert.True(httpResponseMessage.Content.ReadreplacedtringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");
//Missing state - Should succeed
requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", null);
landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
replacedert.Equal<string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
replacedert.NotNull(landingUri.ParseQueryString()["code"]);
replacedert.Equal<bool>(false, landingUri.ParseQueryString().ContainsKey("state"));
//Token endpoint tests
//Invalid client (client_id, client_secret) - As form parameters
var formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "invalid") });
var responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadreplacedtringAsync().Result;
var jToken = JToken.Parse(responseMessage);
replacedert.Equal<string>("invalid_client", jToken.SelectToken("error").Value<string>());
//Invalid client (client_id, client_secret) - As Basic auth headers
responseMessage = basicClient.GetAsync(tokenEndpointUri).Result.Content.ReadreplacedtringAsync().Result;
jToken = JToken.Parse(responseMessage);
replacedert.Equal<string>("invalid_client", jToken.SelectToken("error").Value<string>());
//grant_type=authorization_code - invalid code being sent
formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "authorization_code"), new kvp("code", "InvalidCode"), new kvp("redirect_uri", Client_Redirect_Uri) });
responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadreplacedtringAsync().Result;
jToken = JToken.Parse(responseMessage);
replacedert.Equal<string>("invalid_grant", jToken.SelectToken("error").Value<string>());
//grant_type=authorization_code - Full scenario
requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "validstate");
landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
replacedert.Equal<string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
replacedert.NotNull(landingUri.ParseQueryString()["code"]);
replacedert.Equal<string>("validstate", landingUri.ParseQueryString()["state"]);
formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "authorization_code"), new kvp("code", landingUri.ParseQueryString()["code"]), new kvp("redirect_uri", Client_Redirect_Uri) });
responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadreplacedtringAsync().Result;
jToken = JToken.Parse(responseMessage);
replacedert.NotNull(jToken.SelectToken("access_token").Value<string>());
replacedert.Equal<string>("bearer", jToken.SelectToken("token_type").Value<string>());
replacedert.NotNull(jToken.SelectToken("expires_in").Value<string>());
replacedert.Equal<string>("value1", jToken.SelectToken("param1").Value<string>());
replacedert.Equal<string>("value2", jToken.SelectToken("param2").Value<string>());
replacedert.NotNull(jToken.SelectToken("refresh_token").Value<string>());
//grant_type=preplacedword -- Resource owner credentials -- Invalid credentials
formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "preplacedword"), new kvp("username", "user1"), new kvp("preplacedword", "invalid"), new kvp("scope", "scope1 scope2 scope3") });
responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadreplacedtringAsync().Result;
jToken = JToken.Parse(responseMessage);
replacedert.Equal<string>("invalid_grant", jToken.SelectToken("error").Value<string>());
//grant_type=preplacedword -- Resource owner credentials
formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "preplacedword"), new kvp("username", "user1"), new kvp("preplacedword", "preplacedword1"), new kvp("scope", "scope1 scope2 scope3") });
responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadreplacedtringAsync().Result;
jToken = JToken.Parse(responseMessage);
replacedert.NotNull(jToken.SelectToken("access_token").Value<string>());
replacedert.Equal<string>("bearer", jToken.SelectToken("token_type").Value<string>());
replacedert.NotNull(jToken.SelectToken("expires_in").Value<string>());
replacedert.Equal<string>("value1", jToken.SelectToken("param1").Value<string>());
replacedert.Equal<string>("value2", jToken.SelectToken("param2").Value<string>());
replacedert.NotNull(jToken.SelectToken("refresh_token").Value<string>());
//grant_type=refresh_token -- Use the refresh token issued on the previous call
formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "refresh_token"), new kvp("refresh_token", jToken.SelectToken("refresh_token").Value<string>()), new kvp("scope", "scope1 scope2") });
responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadreplacedtringAsync().Result;
jToken = JToken.Parse(responseMessage);
replacedert.NotNull(jToken.SelectToken("access_token").Value<string>());
replacedert.Equal<string>("bearer", jToken.SelectToken("token_type").Value<string>());
replacedert.NotNull(jToken.SelectToken("expires_in").Value<string>());
replacedert.Equal<string>("value1", jToken.SelectToken("param1").Value<string>());
replacedert.Equal<string>("value2", jToken.SelectToken("param2").Value<string>());
replacedert.NotNull(jToken.SelectToken("refresh_token").Value<string>());
//grant_type=client_credentials - Bug# https://github.com/Katana/katana/issues/562
formContent = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "client_credentials"), new kvp("scope", "scope1 scope2 scope3") });
responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadreplacedtringAsync().Result;
jToken = JToken.Parse(responseMessage);
replacedert.NotNull(jToken.SelectToken("access_token").Value<string>());
replacedert.Equal<string>("bearer", jToken.SelectToken("token_type").Value<string>());
replacedert.NotNull(jToken.SelectToken("expires_in").Value<string>());
replacedert.Equal<string>("value1", jToken.SelectToken("param1").Value<string>());
replacedert.Equal<string>("value2", jToken.SelectToken("param2").Value<string>());
}
finally
{
//Finally close the client endpoint
if (clientEndpoint != null)
{
clientEndpoint.Dispose();
}
}
}
}
19
View Source File : FacebookAuthentication.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
public void FacebookAuthenticationConfiguration(IAppBuilder app)
{
app.UseAuthSignInCookie();
var option = new FacebookAuthenticationOptions()
{
AppId = "550624398330273",
AppSecret = "10e56a291d6b618da61b1e0dae3a8954",
Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = async context =>
{
await Task.Run(() =>
{
if (context.Idenreplacedy != null)
{
replacedert.Equal<string>("ValidAccessToken", context.AccessToken);
replacedert.Equal<string>("[email protected]", context.Email);
replacedert.Equal<string>("Id", context.Id);
replacedert.Equal<string>("https://www.facebook.com/myLink", context.Link);
replacedert.Equal<string>("Owinauthtester Owinauthtester", context.Name);
replacedert.Equal<string>("owinauthtester.owinauthtester.7", context.UserName);
replacedert.Equal<string>(context.Id, context.User.SelectToken("id").ToString());
replacedert.Equal<TimeSpan>(TimeSpan.FromSeconds(100), context.ExpiresIn.Value);
context.Idenreplacedy.AddClaim(new Claim("Authenticated", "true"));
}
}
);
},
OnReturnEndpoint = async context =>
{
await Task.Run(() =>
{
if (context.Idenreplacedy != null && context.SignInAsAuthenticationType == "Application")
{
context.Idenreplacedy.AddClaim(new Claim("ReturnEndpoint", "true"));
context.Idenreplacedy.AddClaim(new Claim(context.Idenreplacedy.RoleClaimType, "Guest", ClaimValueTypes.String));
}
else if (context.Idenreplacedy == null)
{
context.Idenreplacedy = new ClaimsIdenreplacedy("Facebook", "Name_Failed", "Role_Failed");
context.SignInAsAuthenticationType = "Application";
}
});
},
OnApplyRedirect = context =>
{
context.Response.Redirect(context.RedirectUri + "&custom_redirect_uri=custom");
}
},
BackchannelHttpHandler = new FacebookChannelHttpHandler(),
BackchannelCertificateValidator = new CustomCertificateValidator(),
StateDataFormat = new CustomStateDataFormat()
};
option.Scope.Add("read_friendlists");
option.Scope.Add("user_checkins");
app.UseFacebookAuthentication(option);
app.UseExternalApplication("Facebook");
}
19
View Source File : WebSocketTest.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory, Trait("FunctionalTests", "General")]
[InlineData(HostType.HttpListener)]
public async Task WebsocketBasic(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
string applicationUrl = deployer.Deploy(hostType, WebsocketBasicConfiguration);
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(applicationUrl.Replace("http://", "ws://")), CancellationToken.None);
var receiveBody = new byte[100];
for (int i = 0; i < 4; i++)
{
var message = "Message " + i.ToString();
byte[] sendBody = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(sendBody), WebSocketMessageType.Text, true, CancellationToken.None);
var receiveResult = await client.ReceiveAsync(new ArraySegment<byte>(receiveBody), CancellationToken.None);
replacedert.Equal(WebSocketMessageType.Text, receiveResult.MessageType);
replacedert.True(receiveResult.EndOfMessage);
replacedert.Equal(sendBody.Length, receiveResult.Count);
replacedert.Equal(message, Encoding.UTF8.GetString(receiveBody, 0, receiveResult.Count));
}
}
}
}
19
View Source File : WebSocketTest.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
public void WebsocketBasicConfiguration(IAppBuilder app)
{
app.Run(async context =>
{
var acceptWebsocketConnection = context.Get<WebSocketAccept>("websocket.Accept");
if (acceptWebsocketConnection != null)
{
var acceptDictionary = new Dictionary<string, object>();
acceptDictionary.Add("websocket.ReceiveBufferSize", 300);
acceptDictionary.Add("websocket.KeepAliveInterval", TimeSpan.FromMinutes(50));
var websocketBuffer = new ArraySegment<byte>(new byte[1000]);
acceptDictionary.Add("websocket.Buffer", websocketBuffer);
acceptWebsocketConnection(acceptDictionary, async websocketEnvironment =>
{
var sendAsync = websocketEnvironment.Get<WebSocketSendAsync>("websocket.SendAsync");
var receiveAsync = websocketEnvironment.Get<WebSocketReceiveAsync>("websocket.ReceiveAsync");
var closeAsync = websocketEnvironment.Get<WebSocketCloseAsync>("websocket.CloseAsync");
for (int i = 0; i < 4; i++)
{
//Receive data
var receiveBuffer = new ArraySegment<byte>(new byte[100]);
Tuple<int, bool, int> serverReceive = await receiveAsync(receiveBuffer, CancellationToken.None);
replacedert.True(websocketBuffer.Array.Any(b => (b != 0)), "The user provided buffer does not seem to be utilized");
replacedert.Equal("Message " + i.ToString(), Encoding.UTF8.GetString(receiveBuffer.Array, 0, receiveBuffer.Count).TrimEnd('\0'));
//Echo same data back
await sendAsync(new ArraySegment<byte>(receiveBuffer.Array, 0, serverReceive.Item3), serverReceive.Item1, serverReceive.Item2, CancellationToken.None);
}
//Close the connection
await closeAsync((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
});
}
else
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync("Not a web socket connection");
}
});
}
19
View Source File : OwinHostAppSettings.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory, Trait("FunctionalTests", "General")]
[InlineData(HostType.IIS)]
public void FriendlyStartupNameInAppSetting(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
string applicationUrl = deployer.Deploy(hostType);
//Tweek the web.config appSettings to say owin:AppStartup = FriendlyName
var webConfigPath = deployer.GetWebConfigPath();
XmlDoreplacedent configuration = new XmlDoreplacedent() { InnerXml = File.ReadAllText(webConfigPath) };
var appSettingsNode = configuration.SelectSingleNode("/configuration/appSettings");
appSettingsNode.InnerXml += "<add key=\"owin:AppStartup\" value=\"FriendlyClreplacedNameWithMethodNameOverride\" />";
File.WriteAllText(webConfigPath, configuration.InnerXml);
string responseText = HttpClientUtility.GetResponseTextFromUrl(applicationUrl);
replacedert.Equal("CopyOfConfiguration", responseText);
}
}
19
View Source File : OwinHostAppSettings.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact, Trait("FunctionalTests", "General")]
public void ReadAppSettings()
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
var applicationUrl = deployer.Deploy(HostType.IIS, Configuration);
var vDirPath = Path.GetDirectoryName(deployer.GetWebConfigPath());
var options = new MyStartOptions(true) { DontPreplacedStartupClreplacedInCommandLine = true, TargetApplicationDirectory = vDirPath };
string webConfigPath = deployer.GetWebConfigPath();
XmlDoreplacedent configuration = new XmlDoreplacedent() { InnerXml = File.ReadAllText(webConfigPath) };
var appSettingsNode = configuration.SelectSingleNode("/configuration/appSettings");
appSettingsNode.InnerXml += "<add key=\"traceoutput\" value=\"MyLogTextThroughAppSetting.txt\" />";
File.WriteAllText(webConfigPath, configuration.InnerXml);
using (new HostServer(options))
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("outputFile", "Test logging");
string response = httpClient.GetAsync("http://localhost:5000/").Result.Content.ReadreplacedtringAsync().Result;
replacedert.Equal("SUCCESS", response);
replacedert.True(File.Exists("MyLogTextThroughAppSetting.txt"), "Log file MyLogTextThroughAppSetting.txt is not created on specifying through appSetting");
}
}
}
19
View Source File : GoogleOAuth2Authentication.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
public void GoogleOAuth2Configuration(IAppBuilder app)
{
app.UseAuthSignInCookie();
var option = new GoogleOAuth2AuthenticationOptions()
{
ClientId = "581497791735-f9317hcnvcrg9cvl1jfc3tev7teqfump.apps.googleusercontent.com",
ClientSecret = "51LHrC4QaudgKrOQbkfEtz9P",
AccessType = "offline",
Provider = new GoogleOAuth2AuthenticationProvider()
{
OnAuthenticated = async context =>
{
await Task.Run(() =>
{
if (context.Idenreplacedy != null)
{
replacedert.Equal<string>("ValidAccessToken", context.AccessToken);
replacedert.Equal<string>("ValidRefreshToken", context.RefreshToken);
replacedert.Equal<string>("[email protected]", context.Email);
replacedert.Equal<string>("106790274378320830963", context.Id);
replacedert.Equal<string>("owinauthtester2", context.FamilyName);
replacedert.Equal<string>("owinauthtester2 owinauthtester2", context.Name);
replacedert.Equal<TimeSpan>(TimeSpan.FromSeconds(1200), context.ExpiresIn.Value);
replacedert.NotNull(context.User);
context.Idenreplacedy.AddClaim(new Claim("Authenticated", "true"));
}
});
},
OnReturnEndpoint = async context =>
{
await Task.Run(() =>
{
if (context.Idenreplacedy != null && context.SignInAsAuthenticationType == "Application")
{
context.Idenreplacedy.AddClaim(new Claim("ReturnEndpoint", "true"));
context.Idenreplacedy.AddClaim(new Claim(context.Idenreplacedy.RoleClaimType, "Guest", ClaimValueTypes.String));
}
else if (context.Idenreplacedy == null)
{
context.Idenreplacedy = new ClaimsIdenreplacedy("Google", "Name_Failed", "Role_Failed");
context.SignInAsAuthenticationType = "Application";
}
});
},
OnApplyRedirect = context =>
{
context.Response.Redirect(context.RedirectUri + "&custom_redirect_uri=custom");
}
},
BackchannelHttpHandler = new GoogleOAuth2ChannelHttpHandler(),
BackchannelCertificateValidator = new CustomCertificateValidator(),
StateDataFormat = new CustomStateDataFormat()
};
app.UseGoogleAuthentication(option);
app.UseExternalApplication("Google");
}
19
View Source File : MicrosoftAuthentication.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
public void MicrosoftAuthenticationWithProviderConfiguration(IAppBuilder app)
{
app.UseAuthSignInCookie();
var option = new MicrosoftAccountAuthenticationOptions()
{
ClientId = "000000004C0F442C",
ClientSecret = "EkXbW-Vr6Rqzi6pugl1jWIBsDotKLmqR",
Provider = new MicrosoftAccountAuthenticationProvider()
{
OnAuthenticated = async context =>
{
await Task.Run(() =>
{
replacedert.Equal<string>("ValidAccessToken", context.AccessToken);
replacedert.Equal<string>("ValidRefreshToken", context.RefreshToken);
replacedert.Equal<string>("Owinauthtester", context.FirstName);
replacedert.Equal<string>("fccf9a24999f4f4f", context.Id);
replacedert.Equal<string>("Owinauthtester", context.LastName);
replacedert.Equal<string>("Owinauthtester Owinauthtester", context.Name);
replacedert.NotNull(context.User);
replacedert.Equal<string>(context.Id, context.User.SelectToken("id").ToString());
context.Idenreplacedy.AddClaim(new Claim("Authenticated", "true"));
});
},
OnReturnEndpoint = async context =>
{
await Task.Run(() =>
{
if (context.Idenreplacedy != null && context.SignInAsAuthenticationType == "Application")
{
context.Idenreplacedy.AddClaim(new Claim("ReturnEndpoint", "true"));
context.Idenreplacedy.AddClaim(new Claim(context.Idenreplacedy.RoleClaimType, "Guest", ClaimValueTypes.String));
}
else if (context.Idenreplacedy == null)
{
context.Idenreplacedy = new ClaimsIdenreplacedy("Microsoft", "Name_Failed", "Role_Failed");
context.SignInAsAuthenticationType = "Application";
}
});
},
OnApplyRedirect = context =>
{
context.Response.Redirect(context.RedirectUri + "&custom_redirect_uri=custom");
}
},
BackchannelHttpHandler = new MicrosoftChannelHttpHandler(),
BackchannelCertificateValidator = new CustomCertificateValidator(),
StateDataFormat = new CustomStateDataFormat(),
};
app.UseMicrosoftAccountAuthentication(option);
app.UseExternalApplication("Microsoft");
}
19
View Source File : TwitterAuthentication.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
public void TwitterAuthenticationWithProviderConfiguration(IAppBuilder app)
{
app.UseAuthSignInCookie();
app.UseTwitterAuthentication(new TwitterAuthenticationOptions()
{
ConsumerKey = "sgdtlH5fVziF5rAsivNZA",
ConsumerSecret = "lZLT7gEDcBgMrS9lIVzzPUdg61PoJVwfrOlMngaOhg",
Provider = new TwitterAuthenticationProvider()
{
OnAuthenticated = async context =>
{
await Task.Run(() =>
{
replacedert.Equal<string>("valid_user_id", context.UserId);
replacedert.Equal<string>("valid_screen_name", context.ScreenName);
replacedert.Equal<string>("valid_oauth_token", context.AccessToken);
replacedert.Equal<string>("valid_oauth_token_secret", context.AccessTokenSecret);
context.Idenreplacedy.AddClaim(new Claim("Authenticated", "true"));
});
},
OnReturnEndpoint = async context =>
{
await Task.Run(() =>
{
if (context.Idenreplacedy != null && context.SignInAsAuthenticationType == "Application")
{
context.Idenreplacedy.AddClaim(new Claim("ReturnEndpoint", "true"));
context.Idenreplacedy.AddClaim(new Claim(context.Idenreplacedy.RoleClaimType, "Guest", ClaimValueTypes.String));
}
else if (context.Idenreplacedy == null)
{
context.Idenreplacedy = new ClaimsIdenreplacedy("Twitter", "Name_Failed", "Role_Failed");
context.SignInAsAuthenticationType = "Application";
}
});
},
OnApplyRedirect = context =>
{
context.Response.Redirect(context.RedirectUri + "&custom_redirect_uri=custom");
}
},
StateDataFormat = new CustomTwitterRequestTokenFormat(),
BackchannelHttpHandler = new TwitterChannelHttpHandler(),
BackchannelCertificateValidator = new TwitterBackChannelCertificateValidator()
});
app.UseExternalApplication("Twitter");
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData(null, "*", null)]
[InlineData("", "*", null)]
[InlineData("header_not_set", "*", null)]
[InlineData("http://example.com", "*", "*")]
[InlineData("http://example.com", "http://example.com", "http://example.com")]
[InlineData("http://other.com", "http://other.com, http://example.com", "http://other.com")]
[InlineData("http://example.com", "http://other.com, http://example.com", "http://example.com")]
[InlineData("http://invalid.com", "http://example.com", null)]
[InlineData("http://invalid.com", "http://other.com, http://example.com", null)]
public void SendAsync_ReturnsAllowAOrigin(string requestOrigin, string policyOrigin, string expectedOrigin)
{
IAppBuilder builder = new AppBuilder();
var policy = new CorsPolicy();
if (policyOrigin == "*")
{
policy.AllowAnyOrigin = true;
}
else
{
foreach (var o in policyOrigin.Split(','))
{
policy.Origins.Add(o.Trim());
}
}
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
builder.Use((context, next) => Task.FromResult<object>(null));
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/sample");
if ("header_not_set" != requestOrigin)
{
request.Headers.Set(CorsConstants.Origin, requestOrigin);
}
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
string origin = response.Headers.Get("Access-Control-Allow-Origin");
replacedert.Equal(200, response.StatusCode);
replacedert.Equal(expectedOrigin, origin);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("*", "DELETE", "*", "foo,bar")]
[InlineData("http://example.com, http://localhost", "PUT", "http://localhost", "content-type,custom")]
public void SendAsync_Preflight_ReturnsAllowMethodsAndAllowHeaders(string policyOrigin, string requestedMethod, string expectedOrigin, string requestedHeaders)
{
IAppBuilder builder = new AppBuilder();
var policy = new CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true
};
if (policyOrigin == "*")
{
policy.AllowAnyOrigin = true;
}
else
{
foreach (var o in policyOrigin.Split(','))
{
policy.Origins.Add(o.Trim());
}
}
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
builder.Use((context, next) => Task.FromResult<object>(null));
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/sample");
request.Method = "OPTIONS";
request.Headers.Set(CorsConstants.Origin, "http://localhost");
request.Headers.Set(CorsConstants.AccessControlRequestMethod, requestedMethod);
request.Headers.Set(CorsConstants.AccessControlRequestHeaders, requestedHeaders);
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
string origin = response.Headers.Get(CorsConstants.AccessControlAllowOrigin);
string allowMethod = response.Headers.Get(CorsConstants.AccessControlAllowMethods);
string[] allowHeaders = response.Headers.Get(CorsConstants.AccessControlAllowHeaders).Split(',');
string[] requestedHeaderArray = requestedHeaders.Split(',');
replacedert.Equal(200, response.StatusCode);
replacedert.Equal(expectedOrigin, origin);
replacedert.Equal(requestedMethod, allowMethod);
foreach (var requestedHeader in requestedHeaderArray)
{
replacedert.Contains(requestedHeader, allowHeaders);
}
request = CreateRequest("http://localhost/sample");
request.Method = requestedMethod;
request.Headers.Set(CorsConstants.Origin, "http://localhost");
foreach (var requestedHeader in requestedHeaderArray)
{
request.Headers.Set(requestedHeader, requestedHeader);
}
app(request.Environment).Wait();
response = new OwinResponse(request.Environment);
replacedert.Equal(200, response.StatusCode);
replacedert.Equal(expectedOrigin, origin);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void SendAsync_Preflight_ReturnsBadRequest_WhenOriginIsNotAllowed()
{
IAppBuilder builder = new AppBuilder();
var policy = new CorsPolicy();
policy.AllowAnyMethod = true;
policy.AllowAnyHeader = true;
policy.Origins.Add("http://www.example.com");
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/default");
request.Method = "OPTIONS";
request.Headers.Set(CorsConstants.Origin, "http://localhost");
request.Headers.Set(CorsConstants.AccessControlRequestMethod, "POST");
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
string origin = response.Headers.Get(CorsConstants.AccessControlAllowOrigin);
replacedert.Equal(400, response.StatusCode);
replacedert.Equal(null, origin);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void SendAsync_Preflight_ReturnsBadRequest_WhenMethodIsNotAllowed()
{
IAppBuilder builder = new AppBuilder();
var policy = new CorsPolicy();
policy.Methods.Add("DELETE");
policy.AllowAnyHeader = true;
policy.Origins.Add("http://www.example.com");
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/default");
request.Method = "OPTIONS";
request.Headers.Set(CorsConstants.Origin, "http://localhost");
request.Headers.Set(CorsConstants.AccessControlRequestMethod, "POST");
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
string origin = response.Headers.Get(CorsConstants.AccessControlAllowOrigin);
replacedert.Equal(400, response.StatusCode);
replacedert.Equal(null, origin);
}
19
View Source File : CorsMiddlewareTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void SendAsync_Preflight_ReturnsBadRequest_WhenHeaderIsNotAllowed()
{
IAppBuilder builder = new AppBuilder();
var policy = new CorsPolicy();
policy.AllowAnyMethod = true;
policy.Headers.Add("TEST");
policy.Origins.Add("http://www.example.com");
builder.UseCors(new CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(policy)
}
});
var app = (AppFunc)builder.Build(typeof(AppFunc));
IOwinRequest request = CreateRequest("http://localhost/default");
request.Method = "OPTIONS";
request.Headers.Set(CorsConstants.Origin, "http://localhost");
request.Headers.Set(CorsConstants.AccessControlRequestMethod, "POST");
request.Headers.Set(CorsConstants.AccessControlRequestHeaders, "INVALID");
app(request.Environment).Wait();
var response = new OwinResponse(request.Environment);
string origin = response.Headers.Get(CorsConstants.AccessControlAllowOrigin);
replacedert.Equal(400, response.StatusCode);
replacedert.Equal(null, origin);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Environment_Post10Request_ExpectedKeyValueChanges()
{
OwinHttpListener listener = CreateServer(
env =>
{
object ignored;
replacedert.True(env.TryGetValue("owin.RequestMethod", out ignored));
replacedert.Equal("POST", (string)env["owin.RequestMethod"]);
replacedert.True(env.TryGetValue("owin.RequestPath", out ignored));
replacedert.Equal("/SubPath", (string)env["owin.RequestPath"]);
replacedert.True(env.TryGetValue("owin.RequestPathBase", out ignored));
replacedert.Equal("/BaseAddress", (string)env["owin.RequestPathBase"]);
replacedert.True(env.TryGetValue("owin.RequestProtocol", out ignored));
replacedert.Equal("HTTP/1.0", (string)env["owin.RequestProtocol"]);
replacedert.True(env.TryGetValue("owin.RequestQueryString", out ignored));
replacedert.Equal("QueryString", (string)env["owin.RequestQueryString"]);
replacedert.True(env.TryGetValue("owin.RequestScheme", out ignored));
replacedert.Equal("http", (string)env["owin.RequestScheme"]);
replacedert.True(env.TryGetValue("owin.Version", out ignored));
replacedert.Equal("1.0", (string)env["owin.Version"]);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString");
request.Content = new StringContent("Hello World");
request.Version = new Version(1, 0);
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_EmptyGetRequest_RequiredHeadersPresentAndCorrect()
{
OwinHttpListener listener = CreateServer(
env =>
{
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
string[] values;
replacedert.True(requestHeaders.TryGetValue("host", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("localhost:8080", values[0]);
return Task.FromResult(0);
},
HttpServerAddress);
await SendGetRequest(listener, HttpClientAddress);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_MultiValueHeader_NotSplit()
{
OwinHttpListener listener = CreateServer(
env =>
{
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
string[] values;
replacedert.True(requestHeaders.TryGetValue("If-None-Match", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("Value1, value2", values[0]);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Get, HttpClientAddress);
request.Headers.TryAddWithoutValidation("If-None-Match", "Value1, value2");
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_PostContentLengthRequest_RequiredHeadersPresentAndCorrect()
{
string requestBody = "Hello World";
OwinHttpListener listener = CreateServer(
env =>
{
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
string[] values;
replacedert.True(requestHeaders.TryGetValue("host", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("localhost:8080", values[0]);
replacedert.True(requestHeaders.TryGetValue("Content-length", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal(requestBody.Length.ToString(), values[0]);
replacedert.True(requestHeaders.TryGetValue("exPect", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("100-continue", values[0]);
replacedert.True(requestHeaders.TryGetValue("Content-Type", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("text/plain; charset=utf-8", values[0]);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString");
request.Content = new StringContent(requestBody);
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Headers_PostChunkedRequest_RequiredHeadersPresentAndCorrect()
{
string requestBody = "Hello World";
OwinHttpListener listener = CreateServer(
env =>
{
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
string[] values;
replacedert.True(requestHeaders.TryGetValue("host", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("localhost:8080", values[0]);
replacedert.True(requestHeaders.TryGetValue("Transfer-encoding", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("chunked", values[0]);
replacedert.True(requestHeaders.TryGetValue("exPect", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("100-continue", values[0]);
replacedert.True(requestHeaders.TryGetValue("Content-Type", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("text/plain; charset=utf-8", values[0]);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress + "SubPath?QueryString");
request.Headers.TransferEncodingChunked = true;
request.Content = new StringContent(requestBody);
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Body_PostContentLengthZero_NullStream()
{
OwinHttpListener listener = CreateServer(
env =>
{
string[] values;
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
replacedert.True(requestHeaders.TryGetValue("Content-length", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("0", values[0]);
replacedert.NotNull(env.Get<Stream>("owin.RequestBody"));
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
request.Content = new StringContent(string.Empty);
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Body_PostContentLengthX_StreamWithXBytes()
{
OwinHttpListener listener = CreateServer(
env =>
{
string[] values;
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
replacedert.True(requestHeaders.TryGetValue("Content-length", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("11", values[0]);
var requestBody = env.Get<Stream>("owin.RequestBody");
replacedert.NotNull(requestBody);
var buffer = new MemoryStream();
requestBody.CopyTo(buffer);
replacedert.Equal(11, buffer.Length);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
request.Content = new StringContent("Hello World");
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Body_PostChunkedEmpty_StreamWithZeroBytes()
{
OwinHttpListener listener = CreateServer(
env =>
{
string[] values;
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
replacedert.True(requestHeaders.TryGetValue("Transfer-Encoding", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("chunked", values[0]);
var requestBody = env.Get<Stream>("owin.RequestBody");
replacedert.NotNull(requestBody);
var buffer = new MemoryStream();
requestBody.CopyTo(buffer);
replacedert.Equal(0, buffer.Length);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
request.Headers.TransferEncodingChunked = true;
request.Content = new StringContent(string.Empty);
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerRequestTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task Body_PostChunkedX_StreamWithXBytes()
{
OwinHttpListener listener = CreateServer(
env =>
{
string[] values;
var requestHeaders = env.Get<IDictionary<string, string[]>>("owin.RequestHeaders");
replacedert.True(requestHeaders.TryGetValue("Transfer-Encoding", out values));
replacedert.Equal(1, values.Length);
replacedert.Equal("chunked", values[0]);
var requestBody = env.Get<Stream>("owin.RequestBody");
replacedert.NotNull(requestBody);
var buffer = new MemoryStream();
requestBody.CopyTo(buffer);
replacedert.Equal(11, buffer.Length);
return Task.FromResult(0);
},
HttpServerAddress);
var request = new HttpRequestMessage(HttpMethod.Post, HttpClientAddress);
request.Headers.TransferEncodingChunked = true;
request.Content = new StringContent("Hello World");
await SendRequest(listener, request);
}
19
View Source File : OwinHttpListenerTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("/", "", "", "/", "")]
[InlineData("/pathBase", "/pathBase", "/pathBase", "", "")]
[InlineData("/pathBase/", "/pathBase", "/pathBase", "/", "")]
[InlineData("/pathBase/", "/pathBase/", "/pathBase", "/", "")]
[InlineData("/pathBase", "/pathBase/", "/pathBase", "", "")]
[InlineData("/path?query", "", "", "/path", "query")]
[InlineData("/pathBase/path?query", "/pathBase", "/pathBase", "/path", "query")]
public async Task PathAndQueryParsing_CorrectlySeperated(string clientString, string serverBasePath,
string expectedBasePath, string expectedPath, string expectedQuery)
{
var serverAddress = new string[4];
HttpServerAddress.CopyTo(serverAddress, 0);
serverAddress[3] = serverBasePath;
clientString = "http://localhost:8080" + clientString;
OwinHttpListener listener = CreateServer(env =>
{
replacedert.Equal(expectedBasePath, (string)env["owin.RequestPathBase"]);
replacedert.Equal(expectedPath, (string)env["owin.RequestPath"]);
replacedert.Equal(expectedQuery, (string)env["owin.RequestQueryString"]);
return Task.FromResult(0);
}, serverAddress);
using (listener)
{
var client = new HttpClient();
HttpResponseMessage result = await client.GetAsync(clientString);
replacedert.Equal(HttpStatusCode.OK, result.StatusCode);
}
}
19
View Source File : OwinHttpListenerTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("/", "", "", "/", "")]
[InlineData("/path?query", "", "", "/path", "query")]
[InlineData("/pathBase/path?query", "/pathBase", "/pathBase", "/path", "query")]
[InlineData("/pathA/path?query", "/path", "", "/pathA/path", "query")]
public async Task PathAndPathBase_CorrectlySeperated(string clientString, string serverBasePath,
string expectedBasePath, string expectedPath, string expectedQuery)
{
var fallbackAddress = new string[4];
HttpServerAddress.CopyTo(fallbackAddress, 0);
fallbackAddress[3] = "/";
var serverAddress = new string[4];
HttpServerAddress.CopyTo(serverAddress, 0);
serverAddress[3] = serverBasePath;
clientString = "http://localhost:8080" + clientString;
using (var wrapper = new OwinHttpListener())
{
wrapper.Start(wrapper.Listener, env =>
{
replacedert.Equal(expectedBasePath, (string)env["owin.RequestPathBase"]);
replacedert.Equal(expectedPath, (string)env["owin.RequestPath"]);
replacedert.Equal(expectedQuery, (string)env["owin.RequestQueryString"]);
return Task.FromResult(0);
}, CreateAddresses(fallbackAddress, serverAddress), null, null);
using (var client = new HttpClient())
{
HttpResponseMessage result = await client.GetAsync(clientString);
replacedert.Equal(HttpStatusCode.OK, result.StatusCode);
}
}
}
19
View Source File : IntegratedPipelineTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
public override Task Invoke(IOwinContext context)
{
var stage = context.Get<string>("integratedpipeline.CurrentStage");
if (stage != null)
{
replacedert.Equal(_expectedStage, stage);
}
var fullBreadCrumb = context.Get<string>("test.BreadCrumb");
fullBreadCrumb += _crumb;
context.Set("test.BreadCrumb", fullBreadCrumb);
return Next.Invoke(context);
}
19
View Source File : QueryEscapingTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
private void VerifyUriRoundTrip(string input)
{
replacedert.Equal("?" + input, new Uri("http://localhost/?" + input).Query);
}
19
View Source File : ResponseHeadersTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("Microsoft.Owin.Host.SystemWeb")]
[InlineData("Microsoft.Owin.Host.HttpListener")]
public async Task SetSpecialHeaders(string serverName)
{
int port = RunWebServer(
serverName,
SetSpecialHeadersApp);
var client = new HttpClient();
var response = await client.GetAsync("http://localhost:" + port + "/special");
string result = response.Content.ReadreplacedtringAsync().Result;
replacedert.Equal("Hello World", result);
replacedert.Equal((HttpStatusCode)ExpectedStatusCode, response.StatusCode);
foreach (var header in _specialHeaders)
{
IEnumerable<string> values;
bool exists = response.Headers.TryGetValues(header.Key, out values)
|| response.Content.Headers.TryGetValues(header.Key, out values);
replacedert.True(exists);
replacedert.Equal(header.Value, values.First());
}
}
19
View Source File : StaticFilesTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("Microsoft.Owin.Host.SystemWeb")]
[InlineData("Microsoft.Owin.Host.HttpListener")]
public void TooManyRanges_ServeFull(string serverName)
{
int port = RunWebServer(
serverName,
DefaultStaticFiles);
// There's a bug in the 4.0 HttpClientHandler for unbounded ('10-') range header values. Use HWR instead.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:" + port + "/Content/textfile.txt");
request.AddRange(10);
request.AddRange(10);
request.AddRange(10);
request.AddRange(10);
request.AddRange(10);
request.AddRange(10);
request.AddRange(10);
request.AddRange(10);
request.AddRange(10);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("True", string.Join(",", response.Headers.GetValues("PreplacededThroughOWIN")));
replacedert.Equal("text/plain", response.ContentType);
}
19
View Source File : StaticFilesTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("Microsoft.Owin.Host.SystemWeb")]
[InlineData("Microsoft.Owin.Host.HttpListener")]
public async Task ExistingDirectory_Served(string serverName)
{
int port = RunWebServer(
serverName,
DirectoryBrowser);
var client = new HttpClient();
var response = await client.GetAsync("http://localhost:" + port + "/");
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("True", string.Join(",", response.Headers.GetValues("PreplacededThroughOWIN")));
}
19
View Source File : StaticFilesTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("Microsoft.Owin.Host.SystemWeb")]
[InlineData("Microsoft.Owin.Host.HttpListener")]
public async Task ExistingSubDirectory_Served(string serverName)
{
int port = RunWebServer(
serverName,
DirectoryBrowser);
var client = new HttpClient();
var response = await client.GetAsync("http://localhost:" + port + "/Content/");
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("True", string.Join(",", response.Headers.GetValues("PreplacededThroughOWIN")));
}
19
View Source File : SystemWebChunkingCookieManagerTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("name", "value", "name=value; path=/")]
[InlineData("name123", "value456", "name123=value456; path=/")]
[InlineData("[email protected]#$%^&*()_", "[email protected]#$%^&*()_", "name%2B%21%40%23%24%25%5E%26%2A%28%29_=chunks:2; path=/; name%2B%21%40%23%24%25%5E%26%2A%28%29_C1=value%2B%21%40%23%24%25%5E%26%; path=/; name%2B%21%40%23%24%25%5E%26%2A%28%29_C2=2A%28%29_; path=/")]
public async Task AppendCookie(string cookieName, string value, string expected)
{
int port = RunWebServer("Microsoft.Owin.Host.SystemWeb", ChunkingCookieManagerAppendCookieApp);
var client = new HttpClient(new HttpClientHandler() { UseCookies = false });
var message = new HttpRequestMessage(HttpMethod.Get, "http://localhost:" + port + "/AppendCookie");
message.Headers.TryAddWithoutValidation("CookieName", cookieName);
message.Headers.TryAddWithoutValidation("CookieValue", value);
var response = await client.SendAsync(message);
replacedert.Equal("AppendCookieApp", await response.Content.ReadreplacedtringAsync());
IEnumerable<string> values;
replacedert.True(response.Headers.TryGetValues("Set-Cookie", out values));
replacedert.Equal(expected, string.Join("; ", values));
}
19
View Source File : HostingEngineTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public void MultipleUrlsSpecified()
{
var startOptions = new StartOptions();
startOptions.Urls.Add("beta://localhost:3333");
startOptions.Urls.Add("delta://foo/");
startOptions.Urls.Add("gama://*:4444/");
startOptions.Port = 1111; // Ignored because of Url(s)
var serverFactory = new ServerFactoryAlpha();
var startInfo = new StartContext(startOptions);
startInfo.ServerFactory = new ServerFactoryAdapter(serverFactory);
startInfo.App = new AppFunc(env => Task.FromResult(0));
var engine = ServicesFactory.Create().GetService<IHostingEngine>();
serverFactory.InitializeCalled.ShouldBe(false);
serverFactory.CreateCalled.ShouldBe(false);
IDisposable server = engine.Start(startInfo);
serverFactory.InitializeProperties["host.Addresses"].ShouldBeTypeOf<IList<IDictionary<string, object>>>();
var addresses = (IList<IDictionary<string, object>>)serverFactory.InitializeProperties["host.Addresses"];
replacedert.Equal(3, addresses.Count);
var expectedAddresses = new[]
{
new[] { "beta", "localhost", "3333", string.Empty },
new[] { "delta", "foo", string.Empty, "/" },
new[] { "gama", "*", "4444", "/" },
};
for (int i = 0; i < addresses.Count; i++)
{
IDictionary<string, object> addressDictionary = addresses[i];
string[] expectedValues = expectedAddresses[i];
replacedert.Equal(expectedValues.Length, addressDictionary.Count);
replacedert.Equal(expectedValues[0], (string)addressDictionary["scheme"]);
replacedert.Equal(expectedValues[1], (string)addressDictionary["host"]);
replacedert.Equal(expectedValues[2], (string)addressDictionary["port"]);
replacedert.Equal(expectedValues[3], (string)addressDictionary["path"]);
}
server.Dispose();
}
19
View Source File : OwinWebSocketTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Fact]
public async Task EndToEnd_ConnectAndClose_Success()
{
OwinHttpListener listener = CreateServer(env =>
{
var accept = (WebSocketAccept)env["websocket.Accept"];
replacedert.NotNull(accept);
accept(
null,
async wsEnv =>
{
var sendAsync1 = wsEnv.Get<WebSocketSendAsync>("websocket.SendAsync");
var receiveAsync1 = wsEnv.Get<WebSocketReceiveAsync>("websocket.ReceiveAsync");
var closeAsync1 = wsEnv.Get<WebSocketCloseAsync>("websocket.CloseAsync");
var buffer1 = new ArraySegment<byte>(new byte[10]);
await receiveAsync1(buffer1, CancellationToken.None);
await closeAsync1((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
});
return Task.FromResult(0);
},
HttpServerAddress);
using (listener)
{
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);
await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
WebSocketReceiveResult readResult = await client.ReceiveAsync(new ArraySegment<byte>(new byte[10]), CancellationToken.None);
replacedert.Equal(WebSocketCloseStatus.NormalClosure, readResult.CloseStatus);
replacedert.Equal("Closing", readResult.CloseStatusDescription);
replacedert.Equal(0, readResult.Count);
replacedert.True(readResult.EndOfMessage);
replacedert.Equal(WebSocketMessageType.Close, readResult.MessageType);
}
}
}
19
View Source File : PathEscapingTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
private void VerifyUriRoundTrip(string expected)
{
// We know these can't round trip.
string safeExpected = expected
.Replace("%", "%25")
.Replace("?", "%3F")
.Replace("#", "%23")
.Replace(@"\", "%5C");
replacedert.Equal(expected, "/" + new Uri("http://localhost" + safeExpected).GetComponents(UriComponents.Path, UriFormat.Unescaped));
}
19
View Source File : ResponseHeadersTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
public void SetCacheControlApp(IAppBuilder app)
{
app.UseErrorPage(new ErrorPageOptions() { ShowExceptionDetails = true });
app.Run(context =>
{
StreamReader reader = new StreamReader(context.Request.Body);
string cacheHeader = reader.ReadToEnd();
reader.Dispose();
if (!cacheHeader.Equals("DontSet"))
{
bool append = "Append".Equals(context.Request.QueryString.Value);
if (append)
{
foreach (var value in cacheHeader.Split('\0'))
{
context.Response.Headers.AppendValues("Cache-Control", value);
}
}
else
{
context.Response.Headers.SetValues("Cache-Control", cacheHeader.Split('\0'));
}
string roundTrip = context.Response.Headers.Get("Cache-Control");
replacedert.Equal(string.Join(",", cacheHeader.Split('\0')), roundTrip);
}
// Some header issues are only visible after calling write and flush.
context.Response.Write("Hello World");
context.Response.Body.Flush();
return Task.FromResult(0);
});
}
19
View Source File : ResponseHeadersTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("public", "public")]
[InlineData("private", "private")]
[InlineData("public\0private=\"field\"", "public, private=\"field\"")]
[InlineData("no-cache", "no-cache")]
[InlineData("public, no-cache=\"field\"", "public, no-cache=\"field\"")]
[InlineData("no-store", "no-store")]
[InlineData("no-transform", "no-transform")]
[InlineData("must-revalidate", "must-revalidate")]
[InlineData("proxy-revalidate", "proxy-revalidate")]
[InlineData("max-age=1000", "max-age=1000")]
[InlineData("s-maxage=1001", "s-maxage=1001")]
[InlineData("public, max-age=1002", "public, max-age=1002")]
[InlineData("", "")]
[InlineData("DontSet", "private")]
[InlineData("public\0private\0no-cache\0no-store\0no-transform\0must-revalidate\0proxy-revalidate\0max-age=1000\0s-maxage=1001",
"no-store, no-transform, public, must-revalidate, proxy-revalidate, no-cache, max-age=1000, s-maxage=1001, private")]
public void SetCacheControl(string value, string expected)
{
int port = RunWebServer("Microsoft.Owin.Host.SystemWeb", SetCacheControlApp);
var client = new HttpClient();
var response = client.PostAsync("http://localhost:" + port + "/cache-control", new StringContent(value)).Result;
replacedert.Equal("Hello World", response.Content.ReadreplacedtringAsync().Result);
replacedert.Equal(expected, Convert.ToString(response.Headers.CacheControl));
response = client.PostAsync("http://localhost:" + port + "/cache-control?Append", new StringContent(value)).Result;
replacedert.Equal("Hello World", response.Content.ReadreplacedtringAsync().Result);
replacedert.Equal(expected, Convert.ToString(response.Headers.CacheControl));
}
19
View Source File : StaticFilesTests.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory]
[InlineData("Microsoft.Owin.Host.SystemWeb")]
[InlineData("Microsoft.Owin.Host.HttpListener")]
public async Task ManyRanges_ServeFull(string serverName)
{
int port = RunWebServer(
serverName,
DefaultStaticFiles);
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Range", "bytes=0-0,12-12,14-14,16-16,2-2,4-4,6-6,8-8,10-10");
var response = await client.GetAsync("http://localhost:" + port + "/Content/textfile.txt");
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal("True", string.Join(",", response.Headers.GetValues("PreplacededThroughOWIN")));
replacedert.Equal("text/plain", response.Content.Headers.ContentType.ToString());
}
See More Examples