SignalR作为微软提供的web长连接解决方式,十分的好用,但是在项目中实际使用时发现,SignalR对应如何进行身份校验虽然有教程,但是并不是特别容易理解,因此希望将SignalR进行身份校验写下来,方便日后查找。
提示:本文的基础是已经按照官方教程,学会使用SignalR。下面是官方教程。
官方教程地址
实际步骤:
- 1、在hub类中注入IHttpContextAccesser,在客户端连接时校验token
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace SignalRChat.Hubs
{
public class ChatHub : Hub
{
IHttpContextAccessor _httpContextAccessor;
public ChatHub(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public override Task OnConnectedAsync()
{
// 从http中根据“access_token“字段获取,token,然后校验token
string token = _httpContextAccessor.HttpContext.Request.Query["access_token"];
// 实际校验过程根据个人项目决定,成功则连接,不成功直接返回
if(string.IsNullOrEmpty(token))
{
return null
}
return base.OnConnectedAsync();
}
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
- 2、在StartUp.cs中使用HttpContextAccesser
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
// 注意不要使用这种方式
//services.AddScoped<IHttpContextAccessor, HttpContextAccessor>();
}
- 3、配置客户端,使客户端发送的数据带有token,
accessTokenFactory: () => "d2762dbd"
"use strict";
var connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", { accessTokenFactory: () => "d2762dbd" }).build();
//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user) {
console.debug(user);
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
结果展示: