首页 > 解决方案 > 带有 JWT 身份验证的 SignalR Core Android 客户端返回 NULL

问题描述

我正在构建一个与 asp.net core signalR hub 通信的 android 应用程序,没有身份验证,一切都很好,实际上我无法弄清楚。在 Web APi 中,我使用 JWT 进行身份验证并将其作为访问令牌发送回 android 设备,那么如何将令牌发送到集线器?我在文档中找到了这段代码:

HubConnection hubConnection = HubConnectionBuilder.create("https://example.com/myhub")
.withAccessTokenProvider(Single.defer(() -> {
    // Your logic here.
    return Single.just("An Access Token");
})).build();

但我想不通!我应该做什么的逻辑是什么?这也是我的提供者类

public class MyCustomProvider : IUserIdProvider
{
    public string GetUserId(HubConnectionContext connection)
    {
        //throw new NotImplementedException();
        return connection.User?.FindFirst(ClaimTypes.Email).Value?.ToString();
    }
}

这是我的枢纽

public class LocationHub : Hub
{
    private readonly UserManager<ApplicationUser> _userManager;

    public ApplicationDbContext _Context { get; }

    public LocationHub(ApplicationDbContext context, UserManager<ApplicationUser> userManager)
    {
        _Context = context;
        _userManager = userManager;
    }

    public async Task ShareLocation(double Latitude , double Longitude)
    {
        Console.WriteLine("New location from: "+Context.UserIdentifier+"::"+ Latitude + "///" + Longitude);
        await Clients.Others.SendAsync("ReceiveNewLocation", Latitude, Longitude);
    }

    public override  Task OnConnectedAsync()
    {
        var user = _Context.Users.Where(u => u.Email == Context.UserIdentifier).FirstOrDefault();
        user.LoginStatus = true;
        _Context.SaveChanges();
        return base.OnConnectedAsync();
    }

Context.UserIdentifier 为空!!当我尝试这个

PreferencesStore.loadPreferences(this);
    String mToken = PreferencesStore.getToken();
    Log.d("SignalR", mToken);
    hubConnection = HubConnectionBuilder.create("http://myserver/locationhub")
            .withAccessTokenProvider(Single.defer(() -> {

                return Single.just(mToken);
            }))
            .build();

标签: javaandroidasp.net-corejwtsignalr

解决方案


最后找到解决方案,我会把它放在这里以防有人遇到这个问题:

PreferencesStore.loadPreferences(this);
    String mToken = PreferencesStore.getToken();
    hubConnection = HubConnectionBuilder.create("http://myserver/locationhub")
            .withHeader("Authorization", mToken)
            .build();

它与文档不同。我在这里用过.withHeader("Authorization", mToken),但它工作得很好。


推荐阅读