Here are the examples of the csharp api Xunit.Assert.NotNull(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1415 Examples
19
Source : AdminRepositoryGetFeatureDefinitionTest.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
[Fact]
public void CanGetFeatureDefinitionsAll()
{
// Arrange
//Act
var featureDefinitions = repository.GetFeatureDefinitions();
var FDefinitionHealthyWeb = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyWeb.Id);
var FDefinitionHealthySite = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthySite.Id);
var FDefinitionHealthyWebApp = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyWebApp.Id);
var FDefinitionHealthyFarm = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyFarm.Id);
var FDefinitionFaultyWeb = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.FaultyWeb.Id);
var FDefinitionFaultySite = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.FaultySite.Id);
//replacedert
replacedert.NotNull(FDefinitionHealthyWeb);
replacedert.Equal(TestContent.TestFeatures.HealthyWeb.Name, FDefinitionHealthyWeb.Name);
replacedert.Equal(TestContent.TestFeatures.HealthyWeb.replacedle, FDefinitionHealthyWeb.Getreplacedle);
replacedert.Equal(TestContent.TestFeatures.HealthyWeb.Scope, FDefinitionHealthyWeb.Scope);
replacedert.Equal(TestContent.TestFeatures.HealthyWeb.Version, FDefinitionHealthyWeb.DefinitionVersion);
replacedert.Equal(TestContent.TestFeatures.HealthyWeb.Faulty, FDefinitionHealthyWeb.Faulty);
replacedert.Equal(TestContent.TestFeatures.HealthyWeb.TotalActivated, FDefinitionHealthyWeb.ActivatedFeatures.Count);
replacedert.NotNull(FDefinitionHealthySite);
replacedert.Equal(TestContent.TestFeatures.HealthySite.Name, FDefinitionHealthySite.Name);
replacedert.Equal(TestContent.TestFeatures.HealthySite.replacedle, FDefinitionHealthySite.Getreplacedle);
replacedert.Equal(TestContent.TestFeatures.HealthySite.Scope, FDefinitionHealthySite.Scope);
replacedert.Equal(TestContent.TestFeatures.HealthySite.Version, FDefinitionHealthySite.DefinitionVersion);
replacedert.Equal(TestContent.TestFeatures.HealthySite.Faulty, FDefinitionHealthySite.Faulty);
replacedert.Equal(TestContent.TestFeatures.HealthySite.TotalActivated, FDefinitionHealthySite.ActivatedFeatures.Count);
replacedert.NotNull(FDefinitionHealthyWebApp);
replacedert.Equal(TestContent.TestFeatures.HealthyWebApp.Name, FDefinitionHealthyWebApp.Name);
replacedert.Equal(TestContent.TestFeatures.HealthyWebApp.replacedle, FDefinitionHealthyWebApp.Getreplacedle);
replacedert.Equal(TestContent.TestFeatures.HealthyWebApp.Scope, FDefinitionHealthyWebApp.Scope);
replacedert.Equal(TestContent.TestFeatures.HealthyWebApp.Version, FDefinitionHealthyWebApp.DefinitionVersion);
replacedert.Equal(TestContent.TestFeatures.HealthyWebApp.Faulty, FDefinitionHealthyWebApp.Faulty);
replacedert.Equal(TestContent.TestFeatures.HealthyWebApp.TotalActivated, FDefinitionHealthyWebApp.ActivatedFeatures.Count);
replacedert.NotNull(FDefinitionHealthyFarm);
replacedert.Equal(TestContent.TestFeatures.HealthyFarm.Name, FDefinitionHealthyFarm.Name);
replacedert.Equal(TestContent.TestFeatures.HealthyFarm.replacedle, FDefinitionHealthyFarm.Getreplacedle);
replacedert.Equal(TestContent.TestFeatures.HealthyFarm.Scope, FDefinitionHealthyFarm.Scope);
replacedert.Equal(TestContent.TestFeatures.HealthyFarm.Version, FDefinitionHealthyFarm.DefinitionVersion);
replacedert.Equal(TestContent.TestFeatures.HealthyFarm.Faulty, FDefinitionHealthyFarm.Faulty);
replacedert.Equal(TestContent.TestFeatures.HealthyFarm.TotalActivated, FDefinitionHealthyFarm.ActivatedFeatures.Count);
replacedert.NotNull(FDefinitionFaultyWeb);
replacedert.Equal(TestContent.TestFeatures.FaultyWeb.Name, FDefinitionFaultyWeb.Name);
replacedert.Equal(TestContent.TestFeatures.FaultyWeb.replacedle, FDefinitionFaultyWeb.Getreplacedle);
replacedert.Equal(TestContent.TestFeatures.FaultyWeb.Scope, FDefinitionFaultyWeb.Scope);
replacedert.Equal(null, FDefinitionFaultyWeb.DefinitionVersion);
replacedert.Equal(TestContent.TestFeatures.FaultyWeb.Faulty, FDefinitionFaultyWeb.Faulty);
// replacedert.Equal(TestContent.TestFeatures.FaultyWeb.TotalActivated, FDefinitionFaultyWeb.ActivatedFeatures.Count); // for some reasons, 4 are counted, not 3 ... (?)
replacedert.NotNull(FDefinitionFaultySite);
replacedert.Equal(TestContent.TestFeatures.FaultySite.Name, FDefinitionFaultySite.Name);
replacedert.Equal(TestContent.TestFeatures.FaultySite.replacedle, FDefinitionFaultySite.Getreplacedle);
replacedert.Equal(TestContent.TestFeatures.FaultySite.Scope, FDefinitionFaultySite.Scope);
replacedert.Equal(null, FDefinitionFaultySite.DefinitionVersion);
replacedert.Equal(TestContent.TestFeatures.FaultySite.Faulty, FDefinitionFaultySite.Faulty);
// replacedert.Equal(TestContent.TestFeatures.FaultySite.TotalActivated, FDefinitionFaultySite.ActivatedFeatures.Count); // for some reasons, 2 are counted, not 1 ... (?)
}
19
Source : AdminRepositoryGetFeatureDefinitionTest.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
[Fact]
public void CanGetFeatureDefinitionsWeb()
{
// Arrange
//Act
var featureDefinitions = repository.GetFeatureDefinitions(Microsoft.SharePoint.SPFeatureScope.Web);
var FDefinitionHealthyWeb = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyWeb.Id);
var FDefinitionHealthySite = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthySite.Id);
var FDefinitionHealthyWebApp = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyWebApp.Id);
var FDefinitionHealthyFarm = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyFarm.Id);
var FDefinitionFaultyWeb = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.FaultyWeb.Id);
var FDefinitionFaultySite = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.FaultySite.Id);
//replacedert
replacedert.NotNull(FDefinitionHealthyWeb);
replacedert.Null(FDefinitionHealthySite);
replacedert.Null(FDefinitionHealthyWebApp);
replacedert.Null(FDefinitionHealthyFarm);
replacedert.NotNull(FDefinitionFaultyWeb);
replacedert.Null(FDefinitionFaultySite);
}
19
Source : AdminRepositoryGetFeatureDefinitionTest.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
[Fact]
public void CanGetFeatureDefinitionsSite()
{
// Arrange
//Act
var featureDefinitions = repository.GetFeatureDefinitions(Microsoft.SharePoint.SPFeatureScope.Site);
var FDefinitionHealthyWeb = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyWeb.Id);
var FDefinitionHealthySite = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthySite.Id);
var FDefinitionHealthyWebApp = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyWebApp.Id);
var FDefinitionHealthyFarm = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyFarm.Id);
var FDefinitionFaultyWeb = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.FaultyWeb.Id);
var FDefinitionFaultySite = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.FaultySite.Id);
//replacedert
replacedert.Null(FDefinitionHealthyWeb);
replacedert.NotNull(FDefinitionHealthySite);
replacedert.Null(FDefinitionHealthyWebApp);
replacedert.Null(FDefinitionHealthyFarm);
replacedert.Null(FDefinitionFaultyWeb);
replacedert.NotNull(FDefinitionFaultySite);
}
19
Source : AdminRepositoryGetFeatureDefinitionTest.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
[Fact]
public void CanGetFeatureDefinitionsWebApp()
{
// Arrange
//Act
var featureDefinitions = repository.GetFeatureDefinitions(Microsoft.SharePoint.SPFeatureScope.WebApplication);
var FDefinitionHealthyWeb = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyWeb.Id);
var FDefinitionHealthySite = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthySite.Id);
var FDefinitionHealthyWebApp = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyWebApp.Id);
var FDefinitionHealthyFarm = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyFarm.Id);
var FDefinitionFaultyWeb = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.FaultyWeb.Id);
var FDefinitionFaultySite = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.FaultySite.Id);
//replacedert
replacedert.Null(FDefinitionHealthyWeb);
replacedert.Null(FDefinitionHealthySite);
replacedert.NotNull(FDefinitionHealthyWebApp);
replacedert.Null(FDefinitionHealthyFarm);
replacedert.Null(FDefinitionFaultyWeb);
replacedert.Null(FDefinitionFaultySite);
}
19
Source : AdminRepositoryGetFeatureDefinitionTest.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
[Fact]
public void CanGetFeatureDefinitionsFarm()
{
// Arrange
//Act
var featureDefinitions = repository.GetFeatureDefinitions(Microsoft.SharePoint.SPFeatureScope.Farm);
var FDefinitionHealthyWeb = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyWeb.Id);
var FDefinitionHealthySite = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthySite.Id);
var FDefinitionHealthyWebApp = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyWebApp.Id);
var FDefinitionHealthyFarm = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.HealthyFarm.Id);
var FDefinitionFaultyWeb = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.FaultyWeb.Id);
var FDefinitionFaultySite = featureDefinitions.FirstOrDefault(f => f.Id == TestContent.TestFeatures.FaultySite.Id);
//replacedert
replacedert.Null(FDefinitionHealthyWeb);
replacedert.Null(FDefinitionHealthySite);
replacedert.Null(FDefinitionHealthyWebApp);
replacedert.NotNull(FDefinitionHealthyFarm);
replacedert.Null(FDefinitionFaultyWeb);
replacedert.Null(FDefinitionFaultySite);
}
19
Source : AdminRepositoryGetHierarchyTest.cs
with Microsoft Public License
from achimismaili
with Microsoft Public License
from achimismaili
[Fact]
public void ReceiveWebAppsContainsTestWebApp()
{
//Act
var webApps = repository.GetSharePointWebApplications();
var webApp = webApps.FirstOrDefault(w => w.Id == webAppId);
//replacedert
replacedert.NotNull(webApp);
replacedert.Equal(TestContent.SharePointContainers.WebApplication.Url, webApp.Url);
}
19
Source : AccountControllerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void SignInNoScheme_ChallengesAADAzureADDefaultScheme()
{
// Arrange
var controller = new AccountController(
new OptionsMonitor(AzureADDefaults.AuthenticationScheme, new AzureADOptions()
{
OpenIdConnectSchemeName = AzureADDefaults.OpenIdScheme,
CookieSchemeName = AzureADDefaults.CookieScheme
}))
{
Url = new TestUrlHelper("~/", "https://localhost/")
};
// Act
var result = controller.SignIn(null);
// replacedert
var challenge = replacedert.IsreplacedignableFrom<ChallengeResult>(result);
var challengedScheme = replacedert.Single(challenge.AuthenticationSchemes);
replacedert.Equal(AzureADDefaults.AuthenticationScheme, challengedScheme);
replacedert.NotNull(challenge.Properties.RedirectUri);
replacedert.Equal("https://localhost/", challenge.Properties.RedirectUri);
}
19
Source : AccountControllerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void SignInNoScheme_ChallengesAADAzureADB2CDefaultScheme()
{
// Arrange
var controller = new AccountController(
new OptionsMonitor(AzureADB2CDefaults.AuthenticationScheme, new AzureADB2COptions()
{
OpenIdConnectSchemeName = AzureADB2CDefaults.OpenIdScheme,
CookieSchemeName = AzureADB2CDefaults.CookieScheme
}))
{
Url = new TestUrlHelper("~/", "https://localhost/")
};
// Act
var result = controller.SignIn(null);
// replacedert
var challenge = replacedert.IsreplacedignableFrom<ChallengeResult>(result);
var challengedScheme = replacedert.Single(challenge.AuthenticationSchemes);
replacedert.Equal(AzureADB2CDefaults.AuthenticationScheme, challengedScheme);
replacedert.NotNull(challenge.Properties.RedirectUri);
replacedert.Equal("https://localhost/", challenge.Properties.RedirectUri);
}
19
Source : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void AddAzureADB2C_ConfiguresAllOptions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2C(o =>
{
o.Instance = "https://login.microsoftonline.com/tfp";
o.ClientId = "ClientId";
o.ClientSecret = "ClientSecret";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.SignUpSignInPolicyId = "B2C_1_SiUpIn";
o.ResetPreplacedwordPolicyId = "B2C_1_SSPR";
o.EditProfilePolicyId = "B2C_1_SiPe";
});
var provider = services.BuildServiceProvider();
// replacedert
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
replacedert.NotNull(azureADB2COptionsMonitor);
var azureADB2COptions = azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme);
replacedert.Equal(AzureADB2CDefaults.OpenIdScheme, azureADB2COptions.OpenIdConnectSchemeName);
replacedert.Equal(AzureADB2CDefaults.CookieScheme, azureADB2COptions.CookieSchemeName);
replacedert.Equal("https://login.microsoftonline.com/tfp", azureADB2COptions.Instance);
replacedert.Equal("ClientId", azureADB2COptions.ClientId);
replacedert.Equal("ClientSecret", azureADB2COptions.ClientSecret);
replacedert.Equal("/signin-oidc", azureADB2COptions.CallbackPath);
replacedert.Equal("domain.onmicrosoft.com", azureADB2COptions.Domain);
replacedert.Equal("B2C_1_SiUpIn", azureADB2COptions.SignUpSignInPolicyId);
replacedert.Equal("B2C_1_SSPR", azureADB2COptions.ResetPreplacedwordPolicyId);
replacedert.Equal("B2C_1_SiPe", azureADB2COptions.EditProfilePolicyId);
var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
replacedert.NotNull(openIdOptionsMonitor);
var openIdOptions = openIdOptionsMonitor.Get(AzureADB2CDefaults.OpenIdScheme);
replacedert.Equal("ClientId", openIdOptions.ClientId);
replacedert.Equal($"https://login.microsoftonline.com/tfp/domain.onmicrosoft.com/B2C_1_SiUpIn/v2.0", openIdOptions.Authority);
replacedert.True(openIdOptions.UseTokenLifetime);
replacedert.Equal("/signin-oidc", openIdOptions.CallbackPath);
replacedert.Equal(AzureADB2CDefaults.CookieScheme, openIdOptions.SignInScheme);
replacedert.NotNull(openIdOptions.TokenValidationParameters);
replacedert.Equal("name", openIdOptions.TokenValidationParameters.NameClaimType);
replacedert.NotNull(openIdOptions.Events);
var redirectHandler = openIdOptions.Events.OnRedirectToIdenreplacedyProvider;
replacedert.NotNull(redirectHandler);
replacedert.IsType<AzureADB2COpenIDConnectEventHandlers>(redirectHandler.Target);
var remoteFailureHanlder = openIdOptions.Events.OnRemoteFailure;
replacedert.NotNull(remoteFailureHanlder);
replacedert.IsType<AzureADB2COpenIDConnectEventHandlers>(redirectHandler.Target);
}
19
Source : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void AddAzureADB2C_ConfiguresAllOptions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2C(o =>
{
o.Instance = "https://login.microsoftonline.com/tfp";
o.ClientId = "ClientId";
o.ClientSecret = "ClientSecret";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.SignUpSignInPolicyId = "B2C_1_SiUpIn";
o.ResetPreplacedwordPolicyId = "B2C_1_SSPR";
o.EditProfilePolicyId = "B2C_1_SiPe";
});
var provider = services.BuildServiceProvider();
// replacedert
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
replacedert.NotNull(azureADB2COptionsMonitor);
var azureADB2COptions = azureADB2COptionsMonitor.Get(AzureADB2CDefaults.AuthenticationScheme);
replacedert.Equal(AzureADB2CDefaults.OpenIdScheme, azureADB2COptions.OpenIdConnectSchemeName);
replacedert.Equal(AzureADB2CDefaults.CookieScheme, azureADB2COptions.CookieSchemeName);
replacedert.Equal("https://login.microsoftonline.com/tfp", azureADB2COptions.Instance);
replacedert.Equal("ClientId", azureADB2COptions.ClientId);
replacedert.Equal("ClientSecret", azureADB2COptions.ClientSecret);
replacedert.Equal("/signin-oidc", azureADB2COptions.CallbackPath);
replacedert.Equal("domain.onmicrosoft.com", azureADB2COptions.Domain);
replacedert.Equal("B2C_1_SiUpIn", azureADB2COptions.SignUpSignInPolicyId);
replacedert.Equal("B2C_1_SSPR", azureADB2COptions.ResetPreplacedwordPolicyId);
replacedert.Equal("B2C_1_SiPe", azureADB2COptions.EditProfilePolicyId);
var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
replacedert.NotNull(openIdOptionsMonitor);
var openIdOptions = openIdOptionsMonitor.Get(AzureADB2CDefaults.OpenIdScheme);
replacedert.Equal("ClientId", openIdOptions.ClientId);
replacedert.Equal($"https://login.microsoftonline.com/tfp/domain.onmicrosoft.com/B2C_1_SiUpIn/v2.0", openIdOptions.Authority);
replacedert.True(openIdOptions.UseTokenLifetime);
replacedert.Equal("/signin-oidc", openIdOptions.CallbackPath);
replacedert.Equal(AzureADB2CDefaults.CookieScheme, openIdOptions.SignInScheme);
replacedert.NotNull(openIdOptions.TokenValidationParameters);
replacedert.Equal("name", openIdOptions.TokenValidationParameters.NameClaimType);
replacedert.NotNull(openIdOptions.Events);
var redirectHandler = openIdOptions.Events.OnRedirectToIdenreplacedyProvider;
replacedert.NotNull(redirectHandler);
replacedert.IsType<AzureADB2COpenIDConnectEventHandlers>(redirectHandler.Target);
var remoteFailureHanlder = openIdOptions.Events.OnRemoteFailure;
replacedert.NotNull(remoteFailureHanlder);
replacedert.IsType<AzureADB2COpenIDConnectEventHandlers>(redirectHandler.Target);
}
19
Source : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void AddAzureADB2CBearer_AddsAllAuthenticationHandlers()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2CBearer(o => { });
var provider = services.BuildServiceProvider();
// replacedert
replacedert.NotNull(provider.GetService<JwtBearerHandler>());
replacedert.NotNull(provider.GetService<PolicySchemeHandler>());
}
19
Source : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void AddAzureADB2CBearer_ConfiguresAllOptions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2CBearer(o =>
{
o.Instance = "https://login.microsoftonline.com/tfp";
o.ClientId = "ClientId";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.SignUpSignInPolicyId = "B2C_1_SiUpIn";
});
var provider = services.BuildServiceProvider();
// replacedert
var azureADB2COptionsMonitor = provider.GetService<IOptionsMonitor<AzureADB2COptions>>();
replacedert.NotNull(azureADB2COptionsMonitor);
var options = azureADB2COptionsMonitor.Get(AzureADB2CDefaults.BearerAuthenticationScheme);
replacedert.Equal(AzureADB2CDefaults.JwtBearerAuthenticationScheme, options.JwtBearerSchemeName);
replacedert.Equal("https://login.microsoftonline.com/tfp", options.Instance);
replacedert.Equal("ClientId", options.ClientId);
replacedert.Equal("domain.onmicrosoft.com", options.Domain);
replacedert.Equal("B2C_1_SiUpIn", options.DefaultPolicy);
var bearerOptionsMonitor = provider.GetService<IOptionsMonitor<JwtBearerOptions>>();
replacedert.NotNull(bearerOptionsMonitor);
var bearerOptions = bearerOptionsMonitor.Get(AzureADB2CDefaults.JwtBearerAuthenticationScheme);
replacedert.Equal("ClientId", bearerOptions.Audience);
replacedert.Equal($"https://login.microsoftonline.com/tfp/domain.onmicrosoft.com/B2C_1_SiUpIn/v2.0", bearerOptions.Authority);
}
19
Source : AccountControllerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void SignOutNoScheme_SignsOutDefaultCookiesAndDefaultOpenIDConnectAADAzureADSchemesAsync()
{
// Arrange
var options = new AzureADOptions()
{
CookieSchemeName = AzureADDefaults.CookieScheme,
OpenIdConnectSchemeName = AzureADDefaults.OpenIdScheme
};
var controllerContext = CreateControllerContext(
CreateAuthenticatedPrincipal(AzureADDefaults.AuthenticationScheme));
var descriptor = new PageActionDescriptor()
{
AttributeRouteInfo = new AttributeRouteInfo()
{
Template = "/Account/SignedOut"
}
};
var controller = new AccountController(new OptionsMonitor(AzureADDefaults.AuthenticationScheme, options))
{
Url = new TestUrlHelper(
controllerContext.HttpContext,
new RouteData(),
descriptor,
"/Account/SignedOut",
"https://localhost/Account/SignedOut"),
ControllerContext = new ControllerContext()
{
HttpContext = controllerContext.HttpContext
}
};
controller.Request.Scheme = "https";
// Act
var result = controller.SignOut(null);
// replacedert
var signOut = replacedert.IsreplacedignableFrom<SignOutResult>(result);
replacedert.Equal(new[] { AzureADDefaults.CookieScheme, AzureADDefaults.OpenIdScheme }, signOut.AuthenticationSchemes);
replacedert.NotNull(signOut.Properties.RedirectUri);
replacedert.Equal("https://localhost/Account/SignedOut", signOut.Properties.RedirectUri);
}
19
Source : AzureADAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void AddAzureAD_AddsAllAuthenticationHandlers()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureAD(o => { });
var provider = services.BuildServiceProvider();
// replacedert
replacedert.NotNull(provider.GetService<OpenIdConnectHandler>());
replacedert.NotNull(provider.GetService<CookieAuthenticationHandler>());
replacedert.NotNull(provider.GetService<PolicySchemeHandler>());
}
19
Source : AzureADAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void AddAzureAD_ConfiguresAllOptions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureAD(o =>
{
o.Instance = "https://login.microsoftonline.com";
o.ClientId = "ClientId";
o.ClientSecret = "ClientSecret";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.TenantId = "Common";
});
var provider = services.BuildServiceProvider();
// replacedert
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
replacedert.NotNull(azureADOptionsMonitor);
var azureADOptions = azureADOptionsMonitor.Get(AzureADDefaults.AuthenticationScheme);
replacedert.Equal(AzureADDefaults.OpenIdScheme, azureADOptions.OpenIdConnectSchemeName);
replacedert.Equal(AzureADDefaults.CookieScheme, azureADOptions.CookieSchemeName);
replacedert.Equal("https://login.microsoftonline.com", azureADOptions.Instance);
replacedert.Equal("ClientId", azureADOptions.ClientId);
replacedert.Equal("ClientSecret", azureADOptions.ClientSecret);
replacedert.Equal("/signin-oidc", azureADOptions.CallbackPath);
replacedert.Equal("domain.onmicrosoft.com", azureADOptions.Domain);
var openIdOptionsMonitor = provider.GetService<IOptionsMonitor<OpenIdConnectOptions>>();
replacedert.NotNull(openIdOptionsMonitor);
var openIdOptions = openIdOptionsMonitor.Get(AzureADDefaults.OpenIdScheme);
replacedert.Equal("ClientId", openIdOptions.ClientId);
replacedert.Equal($"https://login.microsoftonline.com/Common", openIdOptions.Authority);
replacedert.True(openIdOptions.UseTokenLifetime);
replacedert.Equal("/signin-oidc", openIdOptions.CallbackPath);
replacedert.Equal(AzureADDefaults.CookieScheme, openIdOptions.SignInScheme);
}
19
Source : AzureADAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void AddAzureADBearer_AddsAllAuthenticationHandlers()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADBearer(o => { });
var provider = services.BuildServiceProvider();
// replacedert
replacedert.NotNull(provider.GetService<JwtBearerHandler>());
replacedert.NotNull(provider.GetService<PolicySchemeHandler>());
}
19
Source : AzureADAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void AddAzureADBearer_ConfiguresAllOptions()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADBearer(o =>
{
o.Instance = "https://login.microsoftonline.com/";
o.ClientId = "ClientId";
o.CallbackPath = "/signin-oidc";
o.Domain = "domain.onmicrosoft.com";
o.TenantId = "TenantId";
});
var provider = services.BuildServiceProvider();
// replacedert
var azureADOptionsMonitor = provider.GetService<IOptionsMonitor<AzureADOptions>>();
replacedert.NotNull(azureADOptionsMonitor);
var options = azureADOptionsMonitor.Get(AzureADDefaults.BearerAuthenticationScheme);
replacedert.Equal(AzureADDefaults.JwtBearerAuthenticationScheme, options.JwtBearerSchemeName);
replacedert.Equal("https://login.microsoftonline.com/", options.Instance);
replacedert.Equal("ClientId", options.ClientId);
replacedert.Equal("domain.onmicrosoft.com", options.Domain);
var bearerOptionsMonitor = provider.GetService<IOptionsMonitor<JwtBearerOptions>>();
replacedert.NotNull(bearerOptionsMonitor);
var bearerOptions = bearerOptionsMonitor.Get(AzureADDefaults.JwtBearerAuthenticationScheme);
replacedert.Equal("ClientId", bearerOptions.Audience);
replacedert.Equal($"https://login.microsoftonline.com/TenantId", bearerOptions.Authority);
}
19
Source : AccountControllerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void ResetPreplacedwordNoScheme_ChallengesAADAzureADB2CDefaultSchemeWithResetPreplacedworPolicyAsync()
{
// Arrange
var controller = new AccountController(
new OptionsMonitor(
AzureADB2CDefaults.AuthenticationScheme,
new AzureADB2COptions() { ResetPreplacedwordPolicyId = "Reset" }))
{
Url = new TestUrlHelper("~/", "https://localhost/")
};
controller.ControllerContext = CreateControllerContext(
CreateAuthenticatedPrincipal(AzureADB2CDefaults.AuthenticationScheme));
// Act
var result = controller.ResetPreplacedword(null);
// replacedert
var challenge = replacedert.IsreplacedignableFrom<ChallengeResult>(result);
var challengedScheme = replacedert.Single(challenge.AuthenticationSchemes);
replacedert.Equal(AzureADB2CDefaults.AuthenticationScheme, challengedScheme);
replacedert.NotNull(challenge.Properties.RedirectUri);
replacedert.Equal("https://localhost/", challenge.Properties.RedirectUri);
replacedert.NotNull(challenge.Properties.Items[AzureADB2CDefaults.PolicyKey]);
replacedert.Equal("Reset", challenge.Properties.Items[AzureADB2CDefaults.PolicyKey]);
}
19
Source : AccountControllerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void ResetPreplacedwordCustomScheme_ChallengesAADAzureADB2CDefaultSchemeWithResetPreplacedworPolicyFromCustomSchemeAsync()
{
// Arrange
var controller = new AccountController(
new OptionsMonitor(
"Custom",
new AzureADB2COptions() { ResetPreplacedwordPolicyId = "CustomReset" }))
{
Url = new TestUrlHelper("~/", "https://localhost/")
};
controller.ControllerContext = CreateControllerContext(
CreateAuthenticatedPrincipal("Custom"));
// Act
var result = controller.ResetPreplacedword("Custom");
// replacedert
var challenge = replacedert.IsreplacedignableFrom<ChallengeResult>(result);
var challengedScheme = replacedert.Single(challenge.AuthenticationSchemes);
replacedert.Equal("Custom", challengedScheme);
replacedert.NotNull(challenge.Properties.RedirectUri);
replacedert.Equal("https://localhost/", challenge.Properties.RedirectUri);
replacedert.NotNull(challenge.Properties.Items[AzureADB2CDefaults.PolicyKey]);
replacedert.Equal("CustomReset", challenge.Properties.Items[AzureADB2CDefaults.PolicyKey]);
}
19
Source : AccountControllerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task EditProfileNoScheme_ChallengesAADAzureADB2CCustomSchemeWithEditProfilePolicyAsync()
{
// Arrange
var controller = new AccountController(
new OptionsMonitor(
AzureADB2CDefaults.AuthenticationScheme,
new AzureADB2COptions() { EditProfilePolicyId = "EditProfile" }))
{
Url = new TestUrlHelper("~/", "https://localhost/")
};
controller.ControllerContext = CreateControllerContext(
CreateAuthenticatedPrincipal(AzureADB2CDefaults.AuthenticationScheme));
// Act
var result = await controller.EditProfile(null);
// replacedert
var challenge = replacedert.IsreplacedignableFrom<ChallengeResult>(result);
var challengedScheme = replacedert.Single(challenge.AuthenticationSchemes);
replacedert.Equal(AzureADB2CDefaults.AuthenticationScheme, challengedScheme);
replacedert.NotNull(challenge.Properties.RedirectUri);
replacedert.Equal("https://localhost/", challenge.Properties.RedirectUri);
replacedert.NotNull(challenge.Properties.Items[AzureADB2CDefaults.PolicyKey]);
replacedert.Equal("EditProfile", challenge.Properties.Items[AzureADB2CDefaults.PolicyKey]);
}
19
Source : AccountControllerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task EditProfileCustomScheme_ChallengesAADAzureADB2CCustomSchemeWithEditProfilePolicyFromCustomSchemeAsync()
{
// Arrange
var controller = new AccountController(
new OptionsMonitor(
"Custom",
new AzureADB2COptions() { EditProfilePolicyId = "CustomEditProfile" }))
{
Url = new TestUrlHelper("~/", "https://localhost/")
};
controller.ControllerContext = CreateControllerContext(
CreateAuthenticatedPrincipal("Custom"));
// Act
var result = await controller.EditProfile("Custom");
// replacedert
var challenge = replacedert.IsreplacedignableFrom<ChallengeResult>(result);
var challengedScheme = replacedert.Single(challenge.AuthenticationSchemes);
replacedert.Equal("Custom", challengedScheme);
replacedert.NotNull(challenge.Properties.RedirectUri);
replacedert.Equal("https://localhost/", challenge.Properties.RedirectUri);
replacedert.NotNull(challenge.Properties.Items[AzureADB2CDefaults.PolicyKey]);
replacedert.Equal("CustomEditProfile", challenge.Properties.Items[AzureADB2CDefaults.PolicyKey]);
}
19
Source : AccountControllerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task SignOutNoScheme_SignsOutDefaultCookiesAndDefaultOpenIDConnectAADAzureADB2CSchemesAsync()
{
// Arrange
var options = new AzureADB2COptions()
{
CookieSchemeName = AzureADB2CDefaults.CookieScheme,
OpenIdConnectSchemeName = AzureADB2CDefaults.OpenIdScheme
};
var controllerContext = CreateControllerContext(
CreateAuthenticatedPrincipal(AzureADB2CDefaults.AuthenticationScheme));
var descriptor = new PageActionDescriptor()
{
AttributeRouteInfo = new AttributeRouteInfo()
{
Template = "/Account/SignedOut"
}
};
var controller = new AccountController(new OptionsMonitor(AzureADB2CDefaults.AuthenticationScheme, options))
{
Url = new TestUrlHelper(
controllerContext.HttpContext,
new RouteData(),
descriptor,
"/Account/SignedOut",
"https://localhost/Account/SignedOut"),
ControllerContext = new ControllerContext()
{
HttpContext = controllerContext.HttpContext
}
};
controller.Request.Scheme = "https";
// Act
var result = await controller.SignOut(null);
// replacedert
var signOut = replacedert.IsreplacedignableFrom<SignOutResult>(result);
replacedert.Equal(new[] { AzureADB2CDefaults.CookieScheme, AzureADB2CDefaults.OpenIdScheme }, signOut.AuthenticationSchemes);
replacedert.NotNull(signOut.Properties.RedirectUri);
replacedert.Equal("https://localhost/Account/SignedOut", signOut.Properties.RedirectUri);
}
19
Source : AzureAdB2CAuthenticationBuilderExtensionsTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void AddAzureADB2C_AddsAllAuthenticationHandlers()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(new NullLoggerFactory());
// Act
services.AddAuthentication()
.AddAzureADB2C(o => { });
var provider = services.BuildServiceProvider();
// replacedert
replacedert.NotNull(provider.GetService<OpenIdConnectHandler>());
replacedert.NotNull(provider.GetService<CookieAuthenticationHandler>());
replacedert.NotNull(provider.GetService<PolicySchemeHandler>());
}
19
Source : AuthServerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from 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
Source : FacebookAuthentication.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Theory, Trait("FunctionalTests", "Security")]
[InlineData(HostType.IIS)]
[InlineData(HostType.HttpListener)]
public async Task Security_FacebookAuthentication(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
var applicationUrl = deployer.Deploy(hostType, FacebookAuthenticationConfiguration);
var handler = new HttpClientHandler() { AllowAutoRedirect = false };
var httpClient = new HttpClient(handler);
// Unauthenticated request - verify Redirect url
var response = await httpClient.GetAsync(applicationUrl);
replacedert.Equal<string>("https://www.facebook.com/v2.8/dialog/oauth", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
var queryItems = response.Headers.Location.ParseQueryString();
replacedert.Equal<string>("code", queryItems["response_type"]);
replacedert.Equal<string>("550624398330273", queryItems["client_id"]);
replacedert.Equal<string>(applicationUrl + "signin-facebook", queryItems["redirect_uri"]);
replacedert.Equal<string>("public_profile,email,read_friendlists,user_checkins", queryItems["scope"]);
replacedert.Equal<string>("ValidStateData", queryItems["state"]);
replacedert.Equal<string>("custom", queryItems["custom_redirect_uri"]);
//This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
var correlationCookie = handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Facebook"];
replacedert.NotNull(correlationCookie);
//Invalid state, but valid code
response = await httpClient.GetAsync(GetFacebookSignInMockData(applicationUrl, state: "InvalidStateData"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Application"]);
replacedert.NotNull(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Facebook"]);
//Valid state, but missing code
handler.CookieContainer.Add(correlationCookie);
response = await httpClient.GetAsync(GetFacebookSignInMockData(applicationUrl, code: null));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Facebook"]);
//Valid code & Valid state
handler.CookieContainer.Add(correlationCookie);
response = await httpClient.GetAsync(GetFacebookSignInMockData(applicationUrl));
replacedert.Equal<string>("Facebook", response.Content.ReadreplacedtringAsync().Result);
var cookies = handler.CookieContainer.GetCookies(new Uri(applicationUrl));
replacedert.NotNull(cookies[".AspNet.Application"]);
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Facebook"]);
//Retry with valid credentials for a few times
for (int retry = 0; retry < 4; retry++)
{
response = await httpClient.GetAsync(applicationUrl);
replacedert.Equal<string>("Facebook", response.Content.ReadreplacedtringAsync().Result);
}
//Valid state, but invalid code
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
response = await httpClient.GetAsync(GetFacebookSignInMockData(applicationUrl, code: "InvalidCode"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", response.Content.ReadreplacedtringAsync().Result);
//Valid state, trigger CertValidator
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
response = await httpClient.GetAsync(GetFacebookSignInMockData(applicationUrl, code: "InvalidCert"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", response.Content.ReadreplacedtringAsync().Result);
}
}
19
Source : CookiesAuthCookiePathFact.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Theory, Trait("FunctionalTests", "Security")]
[InlineData(HostType.IIS)]
[InlineData(HostType.HttpListener)]
public void Security_HttpCookieOnlyAndCookiePath(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
string applicationUrl = deployer.Deploy(hostType, HttpCookieOnlyAndCookiePathConfiguration);
string preplacediveAuthLoginPage = applicationUrl + "Auth/PreplacediveAuthLogin";
string homePath = applicationUrl + "Auth/Home";
string logoutPath = applicationUrl + string.Format("Auth/Logout?ReturnUrl={0}", new Uri(homePath).AbsolutePath);
var handler = new HttpClientHandler();
var httpClient = new HttpClient(handler);
var response = httpClient.GetAsync(preplacediveAuthLoginPage).Result;
CookiesCommon.IsRedirectedToCookiesLogin(response.RequestMessage.RequestUri, preplacediveAuthLoginPage, "Unauthenticated requests not automatically redirected to login page");
var validCookieCredentials = new FormUrlEncodedContent(new kvp[] { new kvp("username", "test"), new kvp("preplacedword", "test") });
response = httpClient.PostAsync(response.RequestMessage.RequestUri, validCookieCredentials).Result;
//Verify cookie sent
replacedert.Equal(2, handler.CookieContainer.Count);
CookieCollection cookies = handler.CookieContainer.GetCookies(new Uri(applicationUrl + "Auth"));
Cookie applicationCookie = cookies[CookieAuthenticationDefaults.CookiePrefix + "Application"];
Cookie temporaryCookie = cookies["TemporaryCookie"];
replacedert.NotNull(applicationCookie);
replacedert.NotNull(temporaryCookie);
replacedert.Equal(applicationCookie.HttpOnly, true);
replacedert.Equal(applicationCookie.Path, "/");
replacedert.Equal(temporaryCookie.HttpOnly, false);
replacedert.Equal(temporaryCookie.Path, new Uri(applicationUrl).AbsolutePath + "Auth");
replacedert.Equal<string>(applicationUrl, response.RequestMessage.RequestUri.AbsoluteUri);
//Logout the client
response = httpClient.GetAsync(logoutPath).Result;
replacedert.True(handler.CookieContainer.Count == 0, "Cookie is not cleared on logout");
replacedert.Equal<string>(homePath, response.RequestMessage.RequestUri.AbsoluteUri);
}
}
19
Source : AuthServerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from 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
Source : GoogleOAuth2Authentication.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Theory, Trait("FunctionalTests", "Security")]
[InlineData(HostType.IIS)]
[InlineData(HostType.HttpListener)]
public async Task Security_GoogleOAuth2WithProvider(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
string applicationUrl = deployer.Deploy(hostType, GoogleOAuth2Configuration);
var handler = new HttpClientHandler() { AllowAutoRedirect = false };
var httpClient = new HttpClient(handler);
// Unauthenticated request - verify Redirect url
var response = await httpClient.GetAsync(applicationUrl);
replacedert.Equal<string>("https://accounts.google.com/o/oauth2/v2/auth", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
var queryItems = response.Headers.Location.ParseQueryString();
replacedert.Equal<string>("code", queryItems["response_type"]);
replacedert.Equal<string>("offline", queryItems["access_type"]);
replacedert.Equal<string>("581497791735-f9317hcnvcrg9cvl1jfc3tev7teqfump.apps.googleusercontent.com", queryItems["client_id"]);
replacedert.Equal<string>(applicationUrl + "signin-google", queryItems["redirect_uri"]);
replacedert.Equal<string>("openid profile email", queryItems["scope"]);
replacedert.Equal<string>("ValidStateData", queryItems["state"]);
replacedert.Equal<string>("custom", queryItems["custom_redirect_uri"]);
//This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
var correlationCookie = handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Google"];
replacedert.NotNull(correlationCookie);
//Invalid state, but valid code
response = await httpClient.GetAsync(GetMockData(applicationUrl, state: "InvalidStateData"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Application"]);
replacedert.NotNull(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Google"]);
//Valid state, but missing code
handler.CookieContainer.Add(correlationCookie);
response = await httpClient.GetAsync(GetMockData(applicationUrl, code: null));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Application"]);
//Valid code & Valid state
//handler.CookieContainer.Add(correlationCookie);
response = await httpClient.GetAsync(GetMockData(applicationUrl));
replacedert.Equal<string>("Google", response.Content.ReadreplacedtringAsync().Result);
var cookies = handler.CookieContainer.GetCookies(new Uri(applicationUrl));
replacedert.NotNull(cookies[".AspNet.Application"]);
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Google"]);
//Retry with valid credentials for a few times
for (int retry = 0; retry < 4; retry++)
{
response = await httpClient.GetAsync(applicationUrl);
replacedert.Equal<string>("Google", await response.Content.ReadreplacedtringAsync());
}
//Valid state, but invalid code
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
response = await httpClient.GetAsync(GetMockData(applicationUrl, code: "InvalidCode"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
//Valid state, trigger CertValidator
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
response = await httpClient.GetAsync(GetMockData(applicationUrl, code: "InvalidCert"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
}
}
19
Source : GoogleOAuth2Authentication.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from 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
Source : SymmetricKeyTokenVerification.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact, Trait("FunctionalTests", "Security")]
public void Security_SymmetricKeyTokenVerificationFact()
{
var issuer = "http://katanatesting.com/";
var sentIdenreplacedy = new ClaimsIdenreplacedy("CustomJwt", "MyNameClaimType", "MyRoleClaimType");
sentIdenreplacedy.AddClaims(new Claim[] { new Claim("MyNameClaimType", "TestUser"), new Claim("MyRoleClaimType", "Administrator") });
for (int i = 0; i < 5; i++)
{
sentIdenreplacedy.AddClaim(new Claim("ClaimId" + i.ToString(), i.ToString()));
}
var authProperties = new AuthenticationProperties();
var sentTicket = new AuthenticationTicket(sentIdenreplacedy, authProperties);
var signingAlgorithm = new AesManaged();
var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(signingAlgorithm.Key), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
var tokenValidationParameters = new TokenValidationParameters() { ValidAudience = issuer, SaveSigninToken = true, AuthenticationType = sentIdenreplacedy.AuthenticationType };
var formatter = new JwtFormat(tokenValidationParameters, new SymmetricKeyIssuerSecurityKeyProvider(issuer, signingAlgorithm.Key));
formatter.TokenHandler = new JwtSecurityTokenHandler();
var protectedtext = SecurityUtils.CreateJwtToken(sentTicket, issuer, signingCredentials);
//Receive part
var receivedTicket = formatter.Unprotect(protectedtext);
var receivedClaims = receivedTicket.Idenreplacedy.Claims;
replacedert.Equal<string>("CustomJwt", receivedTicket.Idenreplacedy.AuthenticationType);
replacedert.Equal<string>(ClaimsIdenreplacedy.DefaultNameClaimType, receivedTicket.Idenreplacedy.NameClaimType);
replacedert.Equal<string>(ClaimsIdenreplacedy.DefaultRoleClaimType, receivedTicket.Idenreplacedy.RoleClaimType);
replacedert.NotNull(receivedTicket.Idenreplacedy.BootstrapContext);
replacedert.NotNull((receivedTicket.Idenreplacedy.BootstrapContext) as string);
replacedert.Equal<string>(issuer, receivedClaims.Where<Claim>(claim => claim.Type == "iss").FirstOrDefault().Value);
replacedert.Equal<string>(issuer, receivedClaims.Where<Claim>(claim => claim.Type == "aud").FirstOrDefault().Value);
replacedert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "exp").FirstOrDefault().Value);
for (int i = 0; i < 5; i++)
{
sentIdenreplacedy.AddClaim(new Claim("ClaimId" + i.ToString(), i.ToString()));
replacedert.Equal<string>(i.ToString(), receivedClaims.Where<Claim>(claim => claim.Type == "ClaimId" + i.ToString()).FirstOrDefault().Value);
}
replacedert.Equal<string>("TestUser", receivedClaims.Where<Claim>(claim => claim.Type == ClaimsIdenreplacedy.DefaultNameClaimType).FirstOrDefault().Value);
replacedert.Equal<string>("Administrator", receivedClaims.Where<Claim>(claim => claim.Type == ClaimsIdenreplacedy.DefaultRoleClaimType).FirstOrDefault().Value);
replacedert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "iat").FirstOrDefault().Value);
replacedert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "jti").FirstOrDefault().Value);
}
19
Source : SymmetricKeyTokenVerification.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact, Trait("FunctionalTests", "Security")]
public void Security_SymmetricKeyTokenVerificationFact()
{
var issuer = "http://katanatesting.com/";
var sentIdenreplacedy = new ClaimsIdenreplacedy("CustomJwt", "MyNameClaimType", "MyRoleClaimType");
sentIdenreplacedy.AddClaims(new Claim[] { new Claim("MyNameClaimType", "TestUser"), new Claim("MyRoleClaimType", "Administrator") });
for (int i = 0; i < 5; i++)
{
sentIdenreplacedy.AddClaim(new Claim("ClaimId" + i.ToString(), i.ToString()));
}
var authProperties = new AuthenticationProperties();
var sentTicket = new AuthenticationTicket(sentIdenreplacedy, authProperties);
var signingAlgorithm = new AesManaged();
var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(signingAlgorithm.Key), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
var tokenValidationParameters = new TokenValidationParameters() { ValidAudience = issuer, SaveSigninToken = true, AuthenticationType = sentIdenreplacedy.AuthenticationType };
var formatter = new JwtFormat(tokenValidationParameters, new SymmetricKeyIssuerSecurityKeyProvider(issuer, signingAlgorithm.Key));
formatter.TokenHandler = new JwtSecurityTokenHandler();
var protectedtext = SecurityUtils.CreateJwtToken(sentTicket, issuer, signingCredentials);
//Receive part
var receivedTicket = formatter.Unprotect(protectedtext);
var receivedClaims = receivedTicket.Idenreplacedy.Claims;
replacedert.Equal<string>("CustomJwt", receivedTicket.Idenreplacedy.AuthenticationType);
replacedert.Equal<string>(ClaimsIdenreplacedy.DefaultNameClaimType, receivedTicket.Idenreplacedy.NameClaimType);
replacedert.Equal<string>(ClaimsIdenreplacedy.DefaultRoleClaimType, receivedTicket.Idenreplacedy.RoleClaimType);
replacedert.NotNull(receivedTicket.Idenreplacedy.BootstrapContext);
replacedert.NotNull((receivedTicket.Idenreplacedy.BootstrapContext) as string);
replacedert.Equal<string>(issuer, receivedClaims.Where<Claim>(claim => claim.Type == "iss").FirstOrDefault().Value);
replacedert.Equal<string>(issuer, receivedClaims.Where<Claim>(claim => claim.Type == "aud").FirstOrDefault().Value);
replacedert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "exp").FirstOrDefault().Value);
for (int i = 0; i < 5; i++)
{
sentIdenreplacedy.AddClaim(new Claim("ClaimId" + i.ToString(), i.ToString()));
replacedert.Equal<string>(i.ToString(), receivedClaims.Where<Claim>(claim => claim.Type == "ClaimId" + i.ToString()).FirstOrDefault().Value);
}
replacedert.Equal<string>("TestUser", receivedClaims.Where<Claim>(claim => claim.Type == ClaimsIdenreplacedy.DefaultNameClaimType).FirstOrDefault().Value);
replacedert.Equal<string>("Administrator", receivedClaims.Where<Claim>(claim => claim.Type == ClaimsIdenreplacedy.DefaultRoleClaimType).FirstOrDefault().Value);
replacedert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "iat").FirstOrDefault().Value);
replacedert.NotEmpty(receivedClaims.Where<Claim>(claim => claim.Type == "jti").FirstOrDefault().Value);
}
19
Source : MicrosoftAuthentication.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Theory, Trait("FunctionalTests", "Security")]
[InlineData(HostType.HttpListener)]
public async Task Security_MicrosoftAuthenticationWithProvider(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer("katanatesting.com"))
{
//Edit the hosts file at c:\Windows\System32\drivers\etc\hosts and append this at the end before running the test
//#My entries
//127.0.0.1 katanatesting.com
var hostsFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts");
if (!File.ReadAllText(hostsFilePath).Contains("127.0.0.1 katanatesting.com"))
{
File.AppendAllText(hostsFilePath, "127.0.0.1 katanatesting.com");
}
string applicationUrl = deployer.Deploy(hostType, MicrosoftAuthenticationWithProviderConfiguration);
//Fix application Url hostname
applicationUrl = new UriBuilder(applicationUrl) { Host = "katanatesting.com" }.Uri.AbsoluteUri;
var handler = new HttpClientHandler() { AllowAutoRedirect = false };
var httpClient = new HttpClient(handler);
// Unauthenticated request - verify Redirect url
var response = await httpClient.GetAsync(applicationUrl);
replacedert.Equal<string>("https://login.microsoftonline.com/common/oauth2/v2.0/authorize", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
var queryItems = response.Headers.Location.ParseQueryString();
replacedert.Equal<string>("code", queryItems["response_type"]);
replacedert.Equal<string>("000000004C0F442C", queryItems["client_id"]);
replacedert.Equal<string>(applicationUrl + "signin-microsoft", queryItems["redirect_uri"]);
replacedert.Equal<string>("https://graph.microsoft.com/user.read", queryItems["scope"]);
replacedert.Equal<string>("ValidStateData", queryItems["state"]);
replacedert.Equal<string>("custom", queryItems["custom_redirect_uri"]);
//This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
var correlationCookie = handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Microsoft"];
replacedert.NotNull(correlationCookie);
//Invalid state, but valid code
response = await httpClient.GetAsync(GetMicrosoftSignInMockData(applicationUrl, state: "InvalidStateData"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Application"]);
replacedert.NotNull(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Microsoft"]);
//Valid state, but missing code
handler.CookieContainer.Add(correlationCookie);
response = await httpClient.GetAsync(GetMicrosoftSignInMockData(applicationUrl, code: null));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Microsoft"]);
//Valid code & Valid state
handler.CookieContainer.Add(correlationCookie);
response = await httpClient.GetAsync(GetMicrosoftSignInMockData(applicationUrl));
replacedert.Equal<string>("Microsoft", await response.Content.ReadreplacedtringAsync());
var cookies = handler.CookieContainer.GetCookies(new Uri(applicationUrl));
replacedert.NotNull(cookies[".AspNet.Application"]);
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Microsoft"]);
//Retry with valid credentials for a few times
for (int retry = 0; retry < 4; retry++)
{
response = await httpClient.GetAsync(applicationUrl);
replacedert.Equal<string>("Microsoft", await response.Content.ReadreplacedtringAsync());
}
//Valid state, but invalid code
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
response = await httpClient.GetAsync(GetMicrosoftSignInMockData(applicationUrl, code: "InvalidCode"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
//Valid state, trigger CertValidator
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
response = await httpClient.GetAsync(GetMicrosoftSignInMockData(applicationUrl, code: "InvalidCert"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
}
}
19
Source : MicrosoftAuthentication.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from 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
Source : TwitterAuthentication.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Theory, Trait("FunctionalTests", "Security")]
[InlineData(HostType.HttpListener)]
public async Task Security_TwitterAuthenticationWithProvider(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
string applicationUrl = deployer.Deploy(hostType, TwitterAuthenticationWithProviderConfiguration);
var handler = new HttpClientHandler() { AllowAutoRedirect = false };
var httpClient = new HttpClient(handler);
httpClient.Timeout = new TimeSpan(0, 15, 0);
// Unauthenticated request - verify Redirect url
var response = await httpClient.GetAsync(applicationUrl);
replacedert.Equal<string>("https://api.twitter.com/oauth/authenticate", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
var queryItems = response.Headers.Location.ParseQueryString();
replacedert.Equal<string>("custom", queryItems["custom_redirect_uri"]);
replacedert.NotNull(queryItems["oauth_token"]);
replacedert.NotNull(handler.CookieContainer.GetCookies(new Uri(applicationUrl))["__TwitterState"]);
//This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
//Both oauth_token & oauth_verifier verifier missing - Expect an internal error
response = await httpClient.GetAsync(GetTwitterSignInMockData(applicationUrl, oauth_token: null, oauth_verifier: null));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
//Invalid oauth_token
response = await httpClient.GetAsync(GetTwitterSignInMockData(applicationUrl, oauth_token: "invalid_oauth_token", oauth_verifier: "valid_oauth_verifier"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
//Valid oauth_token & invalid oauth_verifier
response = await httpClient.GetAsync(GetTwitterSignInMockData(applicationUrl, oauth_verifier: "invalid_oauth_verifier"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
//Valid oauth_token & valid oauth_verifier
response = await httpClient.GetAsync(GetTwitterSignInMockData(applicationUrl));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal<string>(response.RequestMessage.RequestUri.AbsoluteUri, applicationUrl);
replacedert.Equal<string>("Twitter", await response.Content.ReadreplacedtringAsync());
replacedert.NotNull(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Application"]);
//Retry multiple times with valid cookie to test sliding expiration
for (int retryCount = 0; retryCount < 3; retryCount++)
{
response = await httpClient.GetAsync(applicationUrl);
replacedert.Equal<string>(response.RequestMessage.RequestUri.AbsoluteUri, applicationUrl);
}
//Trigger cert validation error
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
response = await httpClient.GetAsync(GetTwitterSignInMockData(applicationUrl, oauth_verifier: "InvalidCert"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
}
}
19
Source : OwinHttpListenerRequestTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task CallParameters_EmptyGetRequest_NullBodyNonNullCollections()
{
OwinHttpListener listener = CreateServer(
env =>
{
replacedert.NotNull(env);
replacedert.NotNull(env.Get<Stream>("owin.RequestBody"));
replacedert.NotNull(env.Get<Stream>("owin.ResponseBody"));
replacedert.NotNull(env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"));
replacedert.NotNull(env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"));
return Task.FromResult(0);
},
HttpServerAddress);
await SendGetRequest(listener, HttpClientAddress);
}
19
Source : OwinHttpListenerRequestTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public async Task CallParameters_EmptyGetRequest_NullBodyNonNullCollections()
{
OwinHttpListener listener = CreateServer(
env =>
{
replacedert.NotNull(env);
replacedert.NotNull(env.Get<Stream>("owin.RequestBody"));
replacedert.NotNull(env.Get<Stream>("owin.ResponseBody"));
replacedert.NotNull(env.Get<IDictionary<string, string[]>>("owin.RequestHeaders"));
replacedert.NotNull(env.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"));
return Task.FromResult(0);
},
HttpServerAddress);
await SendGetRequest(listener, HttpClientAddress);
}
19
Source : OwinHttpListenerRequestTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from 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
Source : OwinHttpListenerRequestTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from 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
Source : OwinHttpListenerRequestTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from 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
Source : OwinHttpListenerRequestTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from 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
Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact, Trait("scheme", "https")]
public async Task EndToEnd_HttpsGetRequest_Success()
{
OwinHttpListener listener = CreateServer(
async env =>
{
object obj;
replacedert.True(env.TryGetValue("ssl.LoadClientCertAsync", out obj));
replacedert.NotNull(obj);
replacedert.IsType(typeof(Func<Task>), obj);
var loadCert = (Func<Task>)obj;
await loadCert();
replacedert.True(env.TryGetValue("ssl.ClientCertificate", out obj));
replacedert.NotNull(obj);
replacedert.IsType<X509Certificate2>(obj);
},
HttpsServerAddress);
X509Certificate2 clientCert = FindClientCert();
replacedert.NotNull(clientCert);
HttpResponseMessage response = await SendGetRequest(listener, HttpsClientAddress, clientCert);
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Equal(0, response.Content.Headers.ContentLength.Value);
}
19
Source : ClientCertificateTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Theory, Trait("scheme", "https")]
[InlineData("Microsoft.Owin.Host.SystemWeb")]
[InlineData("Microsoft.Owin.Host.HttpListener")]
public async Task ValidCertProvided_DontAccessCertificate_Success(string serverName)
{
ServicePointManager.ServerCertificateValidationCallback = AcceptAllCerts;
int port = RunWebServer(
serverName,
DontAccessCertificate,
https: true);
X509Certificate2 clientCert = FindClientCert();
replacedert.NotNull(clientCert);
var handler = new WebRequestHandler();
handler.ClientCertificates.Add(clientCert);
var client = new HttpClient(handler);
client.Timeout = TimeSpan.FromSeconds(5);
try
{
var response = await client.GetAsync("https://localhost:" + port);
replacedert.Equal(CertNotFound, response.StatusCode);
}
finally
{
ServicePointManager.ServerCertificateValidationCallback = null;
}
}
19
Source : ClientCertificateTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Theory, Trait("scheme", "https")]
[InlineData("Microsoft.Owin.Host.SystemWeb")]
[InlineData("Microsoft.Owin.Host.HttpListener")]
public async Task ValidCertProvided_CheckClientCertificate_Success(string serverName)
{
ServicePointManager.ServerCertificateValidationCallback = AcceptAllCerts;
int port = RunWebServer(
serverName,
CheckClientCertificate,
https: true);
X509Certificate2 clientCert = FindClientCert();
replacedert.NotNull(clientCert);
var handler = new WebRequestHandler();
handler.ClientCertificates.Add(clientCert);
var client = new HttpClient(handler);
client.Timeout = TimeSpan.FromSeconds(5);
try
{
var response = await client.GetAsync("https://localhost:" + port);
replacedert.Equal(CertFound, response.StatusCode);
}
finally
{
ServicePointManager.ServerCertificateValidationCallback = null;
}
}
19
Source : HostPropertyTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void StartupPropertiesInspection(IAppBuilder app)
{
IDictionary<string, object> properties = app.Properties;
replacedert.NotNull(properties);
var ct = properties.Get<CancellationToken>("host.OnAppDisposing");
replacedert.True(ct.CanBeCanceled);
replacedert.False(ct.IsCancellationRequested);
var appName = properties.Get<string>("host.AppName");
replacedert.NotNull(appName);
var trace = properties.Get<TextWriter>("host.TraceOutput");
replacedert.NotNull(trace);
app.Run(context => { return Task.FromResult(0); });
}
19
Source : ServerFactoryLoaderTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Fact]
public void LoadWithreplacedemblyName_DiscoverDefaultFactoryName()
{
var loader = new ServerFactoryLoader(new ServerFactoryActivator(ServicesFactory.Create()));
IServerFactoryAdapter serverFactory = loader.Load("Microsoft.Owin.Hosting.Tests");
replacedert.NotNull(serverFactory);
IAppBuilder builder = new AppBuilder();
serverFactory.Create(builder);
replacedert.Equal("Microsoft.Owin.Hosting.Tests.OwinServerFactory", builder.Properties["create.server"]);
}
19
Source : ServerFactoryLoaderTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Theory]
[InlineData("Microsoft.Owin.Hosting.Tests.OwinServerFactory")]
[InlineData("Microsoft.Owin.Hosting.Tests.StaticServerFactory")]
[InlineData("Microsoft.Owin.Hosting.Tests.InstanceServerFactory")]
public void LoadWithreplacedemblyAndTypeName_Success(string data)
{
var loader = new ServerFactoryLoader(new ServerFactoryActivator(ServicesFactory.Create()));
IServerFactoryAdapter serverFactory = loader.Load(data);
replacedert.NotNull(serverFactory);
IAppBuilder builder = new AppBuilder();
serverFactory.Create(builder);
replacedert.Equal(data, builder.Properties["create.server"]);
}
19
Source : ServerFactoryLoaderTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Theory]
[InlineData("Microsoft.Owin.Hosting.Tests.OwinServerFactory, Microsoft.Owin.Hosting.Tests, Culture=neutral, PublicKeyToken=null", "Microsoft.Owin.Hosting.Tests.OwinServerFactory")]
[InlineData("Microsoft.Owin.Hosting.Tests.StaticServerFactory, Microsoft.Owin.Hosting.Tests, Culture=neutral, PublicKeyToken=null", "Microsoft.Owin.Hosting.Tests.StaticServerFactory")]
[InlineData("Microsoft.Owin.Hosting.Tests.InstanceServerFactory, Microsoft.Owin.Hosting.Tests, Culture=neutral, PublicKeyToken=null", "Microsoft.Owin.Hosting.Tests.InstanceServerFactory")]
public void LoadWithreplacedemblyAndFullTypeName_Success(string data, string expected)
{
var loader = new ServerFactoryLoader(new ServerFactoryActivator(ServicesFactory.Create()));
IServerFactoryAdapter serverFactory = loader.Load(data);
replacedert.NotNull(serverFactory);
IAppBuilder builder = new AppBuilder();
serverFactory.Create(builder);
replacedert.Equal(expected, builder.Properties["create.server"]);
}
19
Source : HostPropertyTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void StartupPropertiesInspection(IAppBuilder app)
{
IDictionary<string, object> properties = app.Properties;
replacedert.NotNull(properties);
var ct = properties.Get<CancellationToken>("host.OnAppDisposing");
replacedert.True(ct.CanBeCanceled);
replacedert.False(ct.IsCancellationRequested);
var appName = properties.Get<string>("host.AppName");
replacedert.NotNull(appName);
var trace = properties.Get<TextWriter>("host.TraceOutput");
replacedert.NotNull(trace);
app.Run(context => { return Task.FromResult(0); });
}
19
Source : HostPropertyTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public void RuntimePropertiesInspection(IAppBuilder app)
{
app.Run(context =>
{
replacedert.NotNull(context);
var ct = context.Get<CancellationToken>("host.OnAppDisposing");
replacedert.True(ct.CanBeCanceled);
replacedert.False(ct.IsCancellationRequested);
var appName = context.Get<string>("host.AppName");
replacedert.NotNull(appName);
var trace = context.Get<TextWriter>("host.TraceOutput");
replacedert.NotNull(trace);
return Task.FromResult(0);
});
}
19
Source : ServerFactoryLoaderTests.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
[Theory]
[InlineData("Microsoft.Owin.Host.HttpListener")]
[InlineData("Microsoft.Owin.Host.HttpListener.OwinServerFactory")]
public void LoadWithDefaults_LoadreplacedemblyAndDiscoverFactory(string data)
{
var loader = new ServerFactoryLoader(new ServerFactoryActivator(ServicesFactory.Create()));
IServerFactoryAdapter serverFactory = loader.Load(data);
replacedert.NotNull(serverFactory);
IAppBuilder builder = new AppBuilder();
serverFactory.Initialize(builder);
replacedert.IsType<OwinHttpListener>(builder.Properties[typeof(OwinHttpListener).FullName]);
}
See More Examples