我不确定在Asp.Net Core 2.2中是否会发生同样的情况,但是当我升级到最新的Asp.net Core 3版本时,这种情况正在发生。因此,我的问题是我创建了一个自定义AuthenticationHandler
,如下所示:
public class PlatformAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public PlatformAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock)
: base(options, logger, encoder, clock)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var sessionTokenStr = Request.Headers[Headers.SessionToken];
var userTokenStr = Request.Headers[Headers.UserToken];
if (string.IsNullOrEmpty(sessionTokenStr) ||
Guid.TryParse(sessionTokenStr, out var sessionToken))
{
return AuthenticateResult.Fail("Session token should be present and in GUID format");
}
if (string.IsNullOrEmpty(userTokenStr) ||
Guid.TryParse(userTokenStr, out var userToken))
{
return AuthenticateResult.Fail("User token should be present and in GUID format");
}
//... and so on...
}
}
在我的启动课程中,我注册如下身份验证:
collection.AddAuthentication(PlatformScheme.HeaderScheme)
.AddScheme<AuthenticationSchemeOptions, PlatformAuthenticationHandler>(PlatformScheme.HeaderScheme, null);
collection.AddAuthorization();
以及在Configure方法中:
public void Configure(
IApplicationBuilder app)
{
app.UseDeveloperExceptionPage();
app.UseMiddleware<ErrorHandlerMiddleware>();
app.UseCors();
//app.UseMiddleware<SessionBuilderMiddleware>();
app.UseCoreFoundation();//custom library
app.UseStaticFiles();
app.UseStatusCodePages();
app.UseAuthentication();
app.UseAuthorization();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/PlatformApi/swagger.json", "Platform Api");
c.RoutePrefix = "";
});
}
我有一个简单的操作,如下所示:
[HttpGet(UrlPath + "claims")]
[Authorize]
public Task<IDictionary<string, object>> GetClaims(bool refresh)
{
return _authenticationProvider.GetClaimsAsync(refresh);
}
在调试时,我可以看到我返回了AuthenticateResult.Fail("Session token should be present and in GUID format");
,下一步,它进入了GetClaims
方法中。为什么会这样? -如果我从处理程序返回失败,是不是应该阻止我以后再访问该方法?
答案 0 :(得分:4)
中间件的顺序有问题
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
UseAuthentication()
和UseAuthorization()
应该放在UseRouting()
之后和UseEndpoints()
之前,如docs中所述。