我正在尝试在项目中设置集成测试,其中应用程序由 AzureAd (Microsoft.Identity.Web) 和 2FA 保护。通常,用户会使用 SPA 登录到应用程序,并且会受到登录弹出窗口或重定向的欢迎。在测试控制器端点时,没有 SPA,我们也没有使用代表流程,所以我想我可以简单地以通常的方式获取一个令牌来进行测试:
[HttpPost]
public async Task<IActionResult> GetTokenAsync([FromBody] TokenRequest model)
{
_client.BaseAddress = new Uri("https://login.microsoftonline.com/");
var content = new FormUrlEncodedContent(new Dictionary<string, string>
{
/* ... */
}
var response = await _client.PostAsync($"{_options.TenantId}/oauth2/v2.0/token", content);
var responseContent = await response.Content.ReadAsStringAsync();
var token = JsonConvert.DeserializeObject<dynamic>(responseContent);
return Ok(new TokenResponse { Token = token.id_token });
}
但是,由于启用了 2FA,我收到以下错误:
{{
"error": "invalid_grant",
"error_description": "AADSTS50158: External security challenge not satisfied. User will be redirected to another page or authentication provider to satisfy additional authentication
"error_codes": [
50158
],
"timestamp": "2020-12-04 12:41:10Z",
"trace_id": "xxxxxxxxxxxxxx",
"correlation_id": "xxxxxxxxxxxxxxxxxxx",
"error_uri": "https://login.microsoftonline.com/error?code=50158",
"suberror": "basic_action",
"claims": "{ /* ... */}"
}}
更易于阅读的版本:https ://login.microsoftonline.com/error?code=50158
这是身份验证配置的相关部分:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddMicrosoftIdentityWebApi(this.Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(this.Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
/* ... */
}
有没有办法在测试期间满足或规避 2FA 要求,同时保持基本令牌机制完好无损?
更新
以消除任何可能的混淆:我的目标是自动化测试,无需人工干预。我知道,我可以使用带有 custom 的模拟身份验证方案WebApplicationFactory
,但如果可能的话,我会采用一种不那么假的方法。