当前位置:网站首页>Impersonate authentication
Impersonate authentication
2022-07-26 20:08:00 【biyusr】
AuthTests Class to check whether the security endpoint is :
- Redirect unauthenticated users to the login page of the app .
- Return content for authenticated users .
stay SUT in ,/SecurePage Page using AuthorizePage Appointment , take AuthorizeFilter Apply to page . For more information , see also Razor Pages Authorization agreement .
C# Copy
services.AddRazorPages(options =>
{
options.Conventions.AuthorizePage("/SecurePage");
});
stay Get_SecurePageRedirectsAnUnauthenticatedUser In the test , By way of AllowAutoRedirect Set to false, take WebApplicationFactoryClientOptions Set to disallow redirection :
C# Copy
[Fact]
public async Task Get_SecurePageRedirectsAnUnauthenticatedUser()
{
// Arrange
var client = _factory.CreateClient(
new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
// Act
var response = await client.GetAsync("/SecurePage");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.StartsWith("http://localhost/Identity/Account/Login",
response.Headers.Location.OriginalString);
}
By preventing clients from following redirects , The following checks can be performed :
- It can be expected HttpStatusCode.Redirect Results check SUT Status code returned , Instead of the final status code after redirecting to the login page ( This will be HttpStatusCode.OK).
- Check
LocationHeader value , To confirm it withhttp://localhost/Identity/Account/Loginstart , Instead of the final login page response ( amongLocationHeader does not exist ).
Test applications can be found in ConfigureTestServices Middle simulation AuthenticationHandler<TOptions>, To test all aspects of authentication and authorization . The minimum scheme returns AuthenticateResult.Success:
C# Copy
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new[] { new Claim(ClaimTypes.Name, "Test user") };
var identity = new ClaimsIdentity(claims, "Test");
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, "Test");
var result = AuthenticateResult.Success(ticket);
return Task.FromResult(result);
}
}
When the authentication scheme is set to Test( Among them is ConfigureTestServices registered AddAuthentication) when , Would call TestAuthHandler To authenticate users . Test The architecture must match the architecture required by the application , This is important . otherwise , Authentication will not work .
C# Copy
[Fact]
public async Task Get_SecurePageIsReturnedForAnAuthenticatedUser()
{
// Arrange
var client = _factory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddAuthentication("Test")
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(
"Test", options => {});
});
})
.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false,
});
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Test");
//Act
var response = await client.GetAsync("/SecurePage");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
of WebApplicationFactoryClientOptions Details of , see also Client options part .
Set up the environment
By default ,SUT The host and application environment of are configured to use the development environment . Use IHostBuilder Instead of SUT Environment :
- Set up
ASPNETCORE_ENVIRONMENTenvironment variable ( for example ,Staging、ProductionOr other custom values , for exampleTesting). - Replace
CreateHostBuilder, To read toASPNETCOREEnvironment variable with prefix .
C# Copy
protected override IHostBuilder CreateHostBuilder() =>
base.CreateHostBuilder()
.ConfigureHostConfiguration(
config => config.AddEnvironmentVariables("ASPNETCORE"));
If SUT Use Web host (IWebHostBuilder), Replace CreateWebHostBuilder:
C# Copy
protected override IWebHostBuilder CreateWebHostBuilder() =>
base.CreateWebHostBuilder().UseEnvironment("Testing");
Test how the infrastructure infers the application content root path
WebApplicationFactory The constructor searches the assembly containing the integration test for keys equal to TEntryPoint Assembly System.Reflection.Assembly.FullName Of WebApplicationFactoryContentRootAttribute, To infer the application Content root route . If you cannot find an attribute with the correct key , be WebApplicationFactory Will fall back to the search solution file (.sln) And will TEntryPoint The assembly name is appended to the solution directory . Application root ( Content root path ) For discovering views and content files .
Disable shadow copies
Shadow copies cause tests to be performed in a directory different from the output directory . If the test needs to load relative to Assembly.Location The file of , And you have problems , Then you may need to disable shadow copies .
To use xUnit Disable shadow copy when , Please pass Correct configuration settings Create in the test project directory xunit.runner.json file :
JSON Copy
{
"shadowCopy": false
}
Disposal of objects
perform IClassFixture After the test of implementation , When xUnit Management when ,TestServer and WebApplicationFactoryHttpClient Will be disposed of . If the object instantiated by the developer needs to be disposed , Please be there. IClassFixture Dispose of them in implementation . For more information , see also Realization Dispose Method .
Integration test examples
The sample application Contains two applications :
| application | Project directory | describe |
|---|---|---|
| Message application (SUT) | src/RazorPagesProject | Allow users to add messages 、 Delete a message 、 Delete all messages and analysis messages . |
| The test application | tests/RazorPagesProject.Tests | For integration testing SUT. |
You can use IDE Built in test function ( for example Visual Studio) Run the test . If you use Visual Studio Code Or the command line , Please be there. tests/RazorPagesProject.Tests Execute the following command at the command prompt in the directory :
Console copy
dotnet test
Message application (SUT) organization
SUT It has the following characteristics Razor Pages The messaging system :
- Applied index page (
Pages/Index.cshtmlandPages/Index.cshtml.cs) Provide UI And page model method , Used to control adding 、 Delete and analyze messages ( The average number of words per message ). - Message by
Messageclass (Data/Message.cs) describe , And has two properties :Id( key ) andText( news ).TextProperties are required , And limited to 200 Characters . - message In memory database of Entity Framework † Storage .
- Applied to its database context class
AppDbContext(Data/AppDbContext.cs) Contains the data access layer (DAL). - If the database is empty when the application starts , Then the message store is initialized to three messages .
- The application contains
/SecurePage.
†EF The theme Use InMemory To test Explain how to use an in memory database for MSTest test . This topic uses xUnit The test framework . The test concept and test implementation in different test frameworks are similar , But it's not exactly the same .
Although the application does not use repository mode and is not The unit of work (UoW) Pattern A valid example of , but Razor Pages Support these development modes . For more information , see also Design infrastructure persistence layer and Test controller logic ( This example implements the repository pattern ).
Test application organization
The test application is tests/RazorPagesProject.Tests Console applications in the directory .
| Test application directory | describe |
|---|---|
AuthTests | It includes test methods for the following aspects :
|
BasicTests | Contains test methods for routing and content types . |
IntegrationTests | Include using custom WebApplicationFactory Class index page integration test . |
Helpers/Utilities |
|
The test framework is xUnit. Use Microsoft.AspNetCore.TestHost( contain TestServer) Conduct integration test . because Microsoft.AspNetCore.Mvc.Testing Package is used to configure test host and test server , therefore TestHost and TestServer The package does not need to be referenced directly in the project file of the test application or the developer configuration of the test application .
Integration testing usually requires a small data set in the database before executing the test . for example , The deletion test requires the deletion of database records , Therefore, the database must have at least one record , Delete request can succeed .
Example application using Utilities.cs Three messages in ( They can be used when tests are executed ) Seed the database :
C# Copy
public static void InitializeDbForTests(ApplicationDbContext db)
{
db.Messages.AddRange(GetSeedingMessages());
db.SaveChanges();
}
public static void ReinitializeDbForTests(ApplicationDbContext db)
{
db.Messages.RemoveRange(db.Messages);
InitializeDbForTests(db);
}
public static List<Message> GetSeedingMessages()
{
return new List<Message>()
{
new Message(){ Text = "TEST RECORD: You're standing on my scarf." },
new Message(){ Text = "TEST RECORD: Would you like a jelly baby?" },
new Message(){ Text = "TEST RECORD: To the rational mind, " +
"nothing is inexplicable; only unexplained." }
};
}
SUT Database context in its Startup.ConfigureServices Method registration . Test the application of builder.ConfigureServices The callback is executing the application Startup.ConfigureServices Execute after the code . To use different databases for testing , Must be in builder.ConfigureServices Replace the database context of the application in . For more information , see also Customize WebApplicationFactory part .
For still using Web host Of SUT, Test the application of builder.ConfigureServices Callback precedes SUT Of Startup.ConfigureServices Code . Then execute the test application builder.ConfigureTestServices Callback .
边栏推荐
- 银行业务分类
- openstack 虚拟机网卡被重名为cirename0
- [PHP] save session data to redis
- What should we do about the fragmentation of internal information? Try this
- 【OBS】Dropped Frames And General Connection Issues
- C#异步编程看这篇就够了
- [internship experience] date verification
- 学习Muduo中ChatRoom实现的各种细节和思考
- 安全团队:近期Windows版Coremail邮件客户端存在RCE漏洞,可能导致钱包私钥泄露
- [Android] the black technology behind kotlin's rapid compilation. Learn about it~
猜你喜欢

Use of load balancing

超强接口协作平台如何打造:细数Apifox的六把武器

一年卖7亿,德州扒鸡赶考IPO

高瓴加入的PRI,君联、华控、盛世、绿动等百家机构都杀进去了
![Design of intelligent weighing system based on Huawei cloud IOT (STM32) [i]](/img/e4/4ebce448debf4bae308e2d5972a2a2.png)
Design of intelligent weighing system based on Huawei cloud IOT (STM32) [i]

kvm虚拟化

Canvas graphics

.NET GC工作流程

Detailed explanation of Yolo V2

Use request header authentication to test API interfaces that need authorization
随机推荐
numpy.newaxis
【JVM 系列】JVM 调优
计算机专业面试题目总结,总导航
openstack 虚拟机网卡被重名为cirename0
mysql使用union 排序问题
【Pytorch基础】torch.stack()函数解析
Excel-VBA 快速上手(十一、字符串常用操作)
几张图帮你捋清“中国金融机构体系”
高瓴加入的PRI,君联、华控、盛世、绿动等百家机构都杀进去了
Leetcode daily practice - 27. Remove elements
Kingbasees SQL language reference manual of Jincang database (12. SQL statement: alter language to alter subscription)
Zabbix调用api检索方法
【MySQL】 - 索引原理与使用
金融机构导图
Three paradigms of database design
Student‘s t分布
Kingbases SQL language reference manual of Jincang database (13. SQL statement: alter synonym to comment)
千亿酸奶赛道,乳企巨头和新品牌打响拉锯战
Bug feedback: synchronization failed
金仓数据库 KingbaseES SQL 语言参考手册 (18. SQL语句: DROP MATERIALIZED VIEW 到 DROP SYNONYM)