具有JWT身份验证并返回NULL

时间:2020-01-24 16:58:26

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

我正在构建一个与asp.net核心signalR集线器通信的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();

1 个答案:

答案 0 :(得分:0)

最后找到了解决方案,如果有人遇到此问题,我将其放在这里:

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

与文档不同。就在这里,我使用了.withHeader("Authorization", mToken),但是它的工作正常。

相关问题