ASP.Net Core 3-SignalR-忽略[授权]属性

时间:2019-11-18 13:43:22

标签: asp.net-core authorization signalr asp.net-core-3.0 asp.net-core-signalr

将我的项目从ASP.Net Core 2.2升级到3.0后,SignalR授权无法正常工作。 我有一个需要授权的示例中心:

[Authorize]
public class SampleHub : Hub
{
    public int Test() => 123;
}

这是简化的Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddScheme<AuthenticationSchemeOptions, SampleAuthenticationHandler>(JwtBearerDefaults.AuthenticationScheme, null);
    services.AddSignalR();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseRouting();
    app.UseEndpoints(endpoints => endpoints.MapHub<SampleHub>("/samplehub"));
}

简化的身份验证处理程序:

public class SampleAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public SampleAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var result = AuthenticateResult.Fail("Unauthorized");
        return Task.FromResult(result);
    }
}

因此,我希望对我的集线器的请求将由于未授权而失败。但是相反,调用了hub方法并返回测试结果:

var builder = WebHost.CreateDefaultBuilder().UseStartup<Startup>();
var server = new TestServer(builder);
var url = new Uri(server.BaseAddress, "samplehub");
var connection = new HubConnectionBuilder()
    .WithUrl(url, i =>
    {
        i.HttpMessageHandlerFactory = _ => server.CreateHandler();
    }).Build();
await connection.StartAsync();
var result = await connection.InvokeAsync<int>("Test"); // doesn't fail, returns 123

如果集线器具有[Authorize]属性并且AuthenticationHandler将所有请求都标记为失败,为什么它不会失败?

0 个答案:

没有答案
相关问题