java - 带有 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();
解决方案
最后找到解决方案,我会把它放在这里以防有人遇到这个问题:
PreferencesStore.loadPreferences(this);
String mToken = PreferencesStore.getToken();
hubConnection = HubConnectionBuilder.create("http://myserver/locationhub")
.withHeader("Authorization", mToken)
.build();
它与文档不同。我在这里用过.withHeader("Authorization", mToken)
,但它工作得很好。
推荐阅读
- c++ - 套接字接受无效参数(c++)
- ms-access - 访问 VBA:通过函数设置 ComboBox 高度
- ios - UICollectionView AutoSizingCells reloadData()上的奇怪跳转/故障
- java - 尝试安装sas软件时出现以下情况
- php - 选择查询的流明时区相关问题
- python - 给定两个“if”语句,如果其中没有一个被执行,则执行一些代码
- python - TypeError:列表索引必须是整数,而不是 str (MAPNIK)
- flutter - 在 Flutter 中推送新页面时,Navigator 堆栈上的页面会重建
- sql - 我可以在 2 个不同的表中但在 Oracle 的相同列上使用相同的索引吗
- python - Pandas 中的 lambda 函数后索引列消失