【问题标题】:SignalR Core Android client with JWT authintication returning NULL带有 JWT 身份验证的 SignalR Core Android 客户端返回 NULL
【发布时间】:2020-05-11 00:53:11
【问题描述】:

我正在构建一个与 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();

【问题讨论】:

    标签: java android asp.net-core jwt signalr


    【解决方案1】:

    终于找到了解决方案,我会把它放在这里以防万一有人遇到这个问题:

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

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

    【讨论】:

      猜你喜欢
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 2019-10-29
      • 2018-03-25
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      相关资源
      最近更新 更多