signalr核心android客户端,jwt authintation返回null

l2osamch  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(402)

我正在构建一个android应用程序,它可以与asp.net核心signarhub进行通信,没有身份验证,一切都很好,实际上我想不出来。在webapi中,我使用jwt进行身份验证,并将其作为访问令牌发送回android设备,那么如何将令牌发送到hub??我在文档中发现了以下代码:

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();
7xzttuei

7xzttuei1#

最后找到了解决办法,我会把它放在这里,以防有人有这个问题:

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

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

相关问题