I want to pass the renewed token into SignalR requests every time it expires, so that authentication works all the time. And since I have to get the token by an ajax call, from Microsoft documentation we can achieve this by using accessTokenFactory().
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub", {
accessTokenFactory: () => {
// Get and return the access token.
// This function can return a JavaScript Promise if asynchronous
// logic is required to retrieve the access token.
}
})
.build();
But in the below code, if I write the ajax GET call inside the accessTokenFactory function, then it doesn't wait for it to finish (since it is an ajax call) and is calling the server and authentication is failing since the token is not yet present in the query string.
var connection = new signalR.HubConnectionBuilder()
.withUrl(baseUrl + 'hub/report?groupName=' + groupName, {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets,
accessTokenFactory: () =>
{
$.get('api/user/getAccessToken/')
.done(function (token) {
return token;;
})
}
}
)
.withAutomaticReconnect()
.configureLogging(signalR.LogLevel.Debug)
.build();
Can you tell me how to write a ajax call inside the accessTokenFactory function such that it waits for ajax call to finish or how to return a promise (as mentioned in the Microsoft doc code above) in jQuery/JavaScript so that the renewed token is passed along with every SignalR request?
Note: I can use JavaScript or jQuery in my client code.