当前位置:网站首页>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 .
边栏推荐
- 金仓数据库 KingbaseES SQL 语言参考手册 (15. SQL语句:CREATE MATERIALIZED VIEW 到 CREATE SCHEMA)
- Household deposits increased by 10.33 trillion yuan in the first half of the year, with an average of 57.1 billion deposits pouring into banks every day
- 银行业概览
- 靠元宇宙和NFT,天下秀疯狂“割韭菜”?
- Intensive reading of the paper: yolov2 - yolo9000: better, faster, stronger
- [PHP] use file_ get_ Contents() sends get and post requests
- N圆最密堆积、最小外接正方形的matlab求解(二维、三维等圆Packing 问题)
- 一个开源的网页画板,真的太方便了
- Solution to the third game of 2022 Niuke multi school league
- Use request header authentication to test API interfaces that need authorization
猜你喜欢

FastTunnel-开源内网穿透框架
![[internship experience] exception handling and URL result response data processing](/img/ed/05622fad0d3d8dcf17ce7069340669.jpg)
[internship experience] exception handling and URL result response data processing

Excel-VBA 快速上手(十、提示框、可输入的弹出框)

使用ECS和OSS搭建个人网盘

【ffmpeg】给视频文件添加时间戳 汇总

BluePrism流程业务对象的组件功能介绍-RPA第三章

DevOps 实践多年,最痛的居然是?

Software testing - what are the automated testing frameworks?

网络与VPC动手实验

DOM case: 10 second countdown - write jump page related knowledge
随机推荐
客户案例|生学教育依托观测云打造可观测智慧教育新生态
【JVM 系列】JVM 调优
京东荣获中国智能科学技术最高奖!盘点京东体系智能技术
【PHP】常用的header头部定义
[PHP] use file_ get_ Contents() sends get and post requests
go+mysql+redis+vue3简单聊室,第5弹:使用消息队列和定时任务同步消息到mysql
Three paradigms of database design
Collection of original IOS interview questions
go+mysql+redis+vue3简单聊室,第6弹:使用vue3和element-plus调用接口
一个开源的网页画板,真的太方便了
Linux regularly backs up the database and deletes the data n days ago
Kingbasees SQL language reference manual of Jincang database (17. SQL statement: discard to drop language)
Zabbix调用api检索方法
计算机组成原理常见面试题目总结,含答案
【OBS】Dropped Frames And General Connection Issues
花1200亿修一条“地铁”,连接4个万亿城市,广东在想啥?
金融机构盘点
Scope in JS
一年卖7亿,德州扒鸡赶考IPO
Excel-VBA 快速上手(十一、字符串常用操作)