当前位置:网站首页>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 .
边栏推荐
- Is it safe for CSCI qiniu school to open an account? What is qiniu for
- 2022/07/26 learning notes (day16) abstraction and interface
- 数据库笔记(来自老社)
- Design of intelligent weighing system based on Huawei cloud IOT (STM32) [i]
- 试用了多款报表工具,终于找到了基于.Net 6开发的一个了
- 操作系统常见面试题目总结,含答案
- 【Pytorch进阶】pytorch模型的保存与使用
- plsql包
- 千亿酸奶赛道,乳企巨头和新品牌打响拉锯战
- Codeforces Round #810 (Div. 2)(A~C)
猜你喜欢

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

使用ECS和OSS搭建个人网盘

FastTunnel-开源内网穿透框架

猎聘问卷星,成为微信「寄生虫」

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

ShardingSphere-JDBC 关键字问题

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

Detailed explanation of Yolo V2

一文读懂 .NET 中的高性能队列 Channel

Detailed explanation of Yolo v1
随机推荐
Excel-VBA 快速上手(十二、Like 比较的常见用法)
一文看懂中国的金融体系
ShardingSphere-JDBC 关键字问题
负载均衡的使用
TableWidget
openstack 虚拟机网卡被重名为cirename0
直播预约有奖| 高级咨询顾问徐雁斐:效能度量如何助力高效精细的外包管理
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
[internship experience] exception handling and URL result response data processing
Docker使用mysql:5.6和 owncloud 镜像,构建一个个人网盘,安装搭建私有仓库 Harbor
DOM case: 10 second countdown - write jump page related knowledge
Kingbases SQL language reference manual of Jincang database (16. SQL statement: create sequence to delete)
金仓数据库 KingbaseES SQL 语言参考手册 (12. SQL语句:ALTER LANGUAGE 到 ALTER SUBSCRIPTION)
金融机构导图
低代码工具有哪些特色?明眼人都能看出来的低代码两大发展轨迹!
金仓数据库 KingbaseES SQL 语言参考手册 (15. SQL语句:CREATE MATERIALIZED VIEW 到 CREATE SCHEMA)
Use request header authentication to test API interfaces that need authorization
KVM virtualization
Detailed explanation of Yolo v1
Decompile jar files (idea environment)