首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >SignalR核心不使用cookie身份验证

SignalR核心不使用cookie身份验证
EN

Stack Overflow用户
提问于 2018-01-22 17:14:48
回答 2查看 3.8K关注 0票数 2

我似乎不能让SignalR核心与cookie身份验证一起工作。我已经设置了一个测试项目,它可以成功地进行身份验证,并对需要授权的控制器进行后续调用。因此,常规身份验证似乎起作用了。

但之后,当我尝试连接到集线器,然后在标记为Authorize的集线器上触发方法时,调用将失败,并显示以下消息:Authorization failed for user: (null)

我插入了一个虚拟中间件来检查传入的请求。当从我的客户端(xamarin移动应用程序)调用connection.StartAsync()时,我收到一个OPTIONS请求,context.User.Identity.IsAuthenticated等于true。在那之后,我的集线器上的OnConnectedAsync被调用了。在这一点上_contextAccessor.HttpContext.User.Identity.IsAuthenticated是假的。是什么负责解除我的请求的身份验证。从它离开我的中间件开始,到调用OnConnectedAsync的时候,一些东西删除了身份验证。

有什么想法吗?

示例代码:

代码语言:javascript
复制
public class MyMiddleware
{
    private readonly RequestDelegate _next;

    public MyMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {

        await this._next(context);

        //At this point context.User.Identity.IsAuthenticated == true
    }
}

public class TestHub: Hub
{
    private readonly IHttpContextAccessor _contextAccessor;

    public TestHub(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }

    public override async Task OnConnectedAsync()
    {
        //At this point _contextAccessor.HttpContext.User.Identity.IsAuthenticated is false

        await Task.FromResult(1);
    }

    public Task Send(string message)
    {
        return Clients.All.InvokeAsync("Send", message);
    }

    [Authorize]
    public Task SendAuth(string message)
    {
        return Clients.All.InvokeAsync("SendAuth", message + " Authed");
    }
}


public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyContext>(options => options.UseInMemoryDatabase(databaseName: "MyDataBase1"));
        services.AddIdentity<Auth, MyRole>().AddEntityFrameworkStores<MyContext>().AddDefaultTokenProviders();
        services.Configure<IdentityOptions>(options => {

            options.Password.RequireDigit = false;
            options.Password.RequiredLength = 3;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 10;
            options.User.RequireUniqueEmail = true;

        });

        services.AddSignalR();
        services.AddTransient<TestHub>();
        services.AddTransient<MyMiddleware>();

        services.AddAuthentication();
        services.AddAuthorization();
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseMiddleware<MyMiddleware>();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseAuthentication();

        app.UseSignalR(routes =>
        {
            routes.MapHub<TestHub>("TestHub");
        }); 

        app.UseMvc(routes =>
        {
            routes.MapRoute(name: "default", template: "{controller=App}/{action=Index}/{id?}");
        });
    }
}

这是客户端代码:

代码语言:javascript
复制
public async Task Test()
{
    var cookieJar = new CookieContainer();

    var handler = new HttpClientHandler
    {
        CookieContainer = cookieJar,
        UseCookies = true,
        UseDefaultCredentials = false
    };


    var client = new HttpClient(handler);

    var json = JsonConvert.SerializeObject((new Auth { Name = "craig", Password = "12345" }));

    var content = new StringContent(json, Encoding.UTF8, "application/json");

    var result1 = await client.PostAsync("http://localhost:5000/api/My", content); //cookie created

    var result2 = await client.PostAsync("http://localhost:5000/api/My/authtest", content); //cookie tested and works


    var connection = new HubConnectionBuilder()
        .WithUrl("http://localhost:5000/TestHub")
        .WithConsoleLogger()
        .WithMessageHandler(handler)
        .Build();



    connection.On<string>("Send", data =>
    {
        Console.WriteLine($"Received: {data}");
    });

    connection.On<string>("SendAuth", data =>
    {
        Console.WriteLine($"Received: {data}");
    });

    await connection.StartAsync();

    await connection.InvokeAsync("Send", "Hello"); //Succeeds, no auth required

    await connection.InvokeAsync("SendAuth", "Hello NEEDSAUTH"); //Fails, auth required

}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-01-23 03:31:21

看起来这是WebSocketsTransport中的一个问题,我们没有将Cookie复制到websocket选项中。我们目前只复制标题。我会提出一个问题,让它看一看。

票数 1
EN

Stack Overflow用户

发布于 2018-06-03 05:16:40

如果您使用的是Core2,请尝试更改UseAuthentication的顺序,将其放在UseSignalR方法之前。

代码语言:javascript
复制
 app.UseAuthentication();
 app.UseSignalR...

那么在集线器内部,Identity属性不应该为空。

代码语言:javascript
复制
Context.User.Identity.Name
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48378073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档