Replies: 2 comments 12 replies
-
I made some changes in the This is the new <!DOCTYPE html>
<html>
<body>
<h2>SignalR Chat Client</h2>
<div>
<label for="token">JWT Token:</label>
<input type="text" id="token" placeholder="Enter your JWT Token">
</div>
<div>
<label for="userAId">Your User ID:</label>
<input type="text" id="userAId" placeholder="Enter your user ID">
</div>
<div>
<label for="userAName">Your Name:</label>
<input type="text" id="userAName" placeholder="Enter your name">
</div>
<div>
<label for="userBId">Recipient's User ID:</label>
<input type="text" id="userBId" placeholder="Enter recipient's user ID">
</div>
<div>
<label for="userBName">Recipient's Name:</label>
<input type="text" id="userBName" placeholder="Enter recipient's name">
</div>
<div>
<label for="roomName">Room Name:</label>
<input type="text" id="roomName" placeholder="Enter the Room Name">
</div>
<div>
<label for="message">Message:</label>
<input type="text" id="message" placeholder="Enter your message">
</div>
<button id="sendMessage">Send Message</button>
<h3>Messages:</h3>
<ul id="messagesList"></ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.12/signalr.min.js"></script>
<script>
let connection;
window.onload = function () {
console.log("Page loaded and script running");
document.getElementById("sendMessage").addEventListener("click", function () {
console.log("Button clicked");
const token = document.getElementById("token").value;
const userAId = document.getElementById("userAId").value;
const userAName = document.getElementById("userAName").value;
const userBId = document.getElementById("userBId").value;
const userBName = document.getElementById("userBName").value;
const roomName = document.getElementById("roomName").value;
const message = document.getElementById("message").value;
if (!token || !userAId || !userAName || !userBId || !userBName || !roomName || !message) {
alert("All fields are required: JWT Token, User ID, Your Name, Recipient's User ID, Recipient's Name, Room Name, and Message!");
return;
}
const decodedToken = parseJwt(token);
console.log("Decoded Token: ", decodedToken);
const currentTimestamp = Math.floor(Date.now() / 1000);
if (decodedToken.exp < currentTimestamp) {
alert("The JWT token has expired. Please generate a new one.");
return;
}
let userRole = decodedToken["http://schemas.microsoft.com/ws/2008/06/identity/claims/role"];
if (!userRole || (userRole !== "Base User" && userRole !== "Admin" && userRole !== "Developer Admin")) {
alert("The JWT token must include a valid role ('Base User', 'Admin', or 'Developer Admin').");
return;
}
if (!connection) {
console.log("Using token for SignalR connection: ", token);
connection = new signalR.HubConnectionBuilder()
.withUrl("https://localhost:44300/chathub?room=" + encodeURIComponent(roomName), {
accessTokenFactory: () => {
console.log("Token being used: ", token);
return token }
})
.configureLogging(signalR.LogLevel.Trace) // Detailed logging for troubleshooting
.build();
connection.start()
.then(() => {
console.log("Connected to SignalR");
connection.invoke("SendMessageToRoom", roomName, userAId, userAName, userBId, userBName, message)
.then(() => {
console.log("Message sent to room:", roomName);
})
.catch(err => {
console.error("Error sending message:", err.message);
alert("Failed to send the message: " + err.message);
});
})
.catch(err => {
console.error("Failed to connect to SignalR. Error message: ", err.message);
alert("Failed to connect to SignalR. Error message: " + err.message);
});
connection.on("ReceiveMessage", (user, message) => {
const msg = document.createElement("li");
msg.textContent = `${user}: ${message}`;
document.getElementById("messagesList").appendChild(msg);
});
} else {
connection.invoke("SendMessageToRoom", roomName, userAId, userAName, userBId, userBName, message)
.then(() => {
console.log("Message sent to room:", roomName);
})
.catch(err => console.error("Error sending message:", err));
}
});
};
function parseJwt(token) {
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload);
} catch (e) {
console.error("Error decoding token:", e);
return null;
}
}
</script>
</body>
</html> |
Beta Was this translation helpful? Give feedback.
-
💡The problem seems to be if I pass my
I initialize my var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddOrchardCms()
.ConfigureServices(services =>
{
ConfigurationModel config = builder.Configuration.Get<ConfigurationModel>();
if (config == null)
{
throw new Exception("Was impossible to retrieve the appsettings.json configuration. Please check the appsettings file.");
}
services.AddHttpClient();
// Add Parts
services.AddContentPart<ChatMessage>();
services.AddContentPart<ChatRoom>();
// Add Handlers
services.AddScoped<IChatHandler, ChatHandler>(x => new ChatHandler(x.GetRequiredService<IContentManager>(), x.GetRequiredService<YesSql.ISession>(), x.GetRequiredService<ILogger<ChatHandler>>()));
});
builder.Services.AddSignalR();
[...]
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub"); // The endpoint for the SignalR hub
});
app.Run(); @Piedone @hishamco do you know how can I pass in dependency injection my Thank you |
Beta Was this translation helpful? Give feedback.
-
Hi everyone,
I'm trying to implement an Orchard Core microservice that uses SignalR for chat functionality. Essentially, the Angular client app will handle most of the front-end work, while Orchard Core 1.8.2 will be used to store the message history. To achieve this, I have installed
Microsoft.AspNetCore.SignalR.Common 8.0.10
and created aChatHub : Hub
class to send messages.However, I encounter a 401 Error whenever I add the
[Authorize]
attribute to theChatHub
(using the same approach that successfully authenticates my API endpoints). So I tried to remove the Authorize to check if SignalR is working, but I get a SignalR connection error that says:Error connecting to SignalR: Promise.catch
.My environment:
Microsoft.AspNetCore.SignalR.Common
, version8.0.10
;ChatHub
class to manage sending messages (and later saving them in the Orchard Core database).Questions:
How can I make this work? Is there another way to implement it or an official module? 🤔
Below is some of the code I wrote.
The
Program.cs
:My
ChatHub.cs
:My
Controller.cs
to serve the client page:My
client
html:Thank you 😊
Beta Was this translation helpful? Give feedback.
All reactions