简体   繁体   中英

How to catch 401 Unauthorized from SignalR after token expired

I have built an page that gets real-time data from my azure functions backend via SignalR. Lets say i stay on the page, watching the data for 1 hour, and i might get a disconnect, the signalr client will try to reconnect automatically, this works fine. But when it tries to reconnect the jwt token might have expired and a 401 is throw from the signalr client.

Is there any way to catch this 401 from the signalr client when a reconnect is fired?

Many people seems to use.onclose() but will not work for me, or fetching a new jwt token every time they connect, i guess this might be the way i need to proceed, but i prefer if it would be possible to catch it instead, that would be a better fix in my opinion.

var connection = new signalR.HubConnectionBuilder()
                .configureLogging(signalR.LogLevel.Information)
                .withUrl(config.default.hostname + "/api/v1/core/signalr",
                    { accessTokenFactory: () => store.state.accessToken })
                .withAutomaticReconnect([0, 0, 10000])
                .build();

connection.start();

Hope you understand what I'm looking for here! Cheers!

That is why on the { accessTokenFactory: () => store.state.accessToken } you should pass a function that will refresh the token. So when the token expires, it will automatically check for new token from this method. So don't store the token in store.state.accessToken ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM