Meine Frage ist, dass ich nicht weiß, wie ich das Problem beheben kann. Ich habe verschiedene Dinge ausprobiert, aber nichts scheint zu helfen, warum das JWT-Token nicht zurückgesendet wird, damit es vom Back-End autorisiert werden kann.
Code: Select all
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
// Log all cookies
Console.WriteLine("=== OnMessageReceived ===");
Console.WriteLine($"Cookies received: {string.Join(", ", context.Request.Cookies.Keys)}");
// 1) SignalR websocket transports send access_token in query string
var accessToken = context.Request.Query["access_token"].FirstOrDefault();
if (!string.IsNullOrEmpty(accessToken))
{
Console.WriteLine(" Token found in query string");
context.Token = accessToken;
return Task.CompletedTask;
}
// 2) fallback to the AuthToken cookie
if (context.Request.Cookies.TryGetValue("AuthToken", out var cookieToken) && !string.IsNullOrEmpty(cookieToken))
{
Console.WriteLine($" Token found in AuthToken cookie: {cookieToken.Substring(0, 20)}...");
context.Token = cookieToken;
}
else
{
Console.WriteLine(" No AuthToken cookie found!");
}
return Task.CompletedTask;
}
};
Code: Select all
render() {
const root = document.createElement('div');
root.innerHTML = `
Users
Search
Chat no one
Send Refresh
`;
root.querySelector('#searchBtn').addEventListener('click', async ()=> {
const q = root.querySelector('#search').value;
const res = await fetch(API + '/api/Users/search?q=' + encodeURIComponent(q), { withCredentials: true });
const users = await res.json();
const usersEl = root.querySelector('#users');
usersEl.innerHTML = '';
users.forEach(u=> {
Code: Select all
using ChatBackendFinal.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ChatBackendFinal.Controllers
{
[ApiController]
[Route("api/Users")]
[Authorize(Policy = "AuthenticatedUsersOnly")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
public UsersController(IUserService userService)
{
_userService = userService;
}
[HttpGet("search")]
public async Task SearchUsers([FromQuery] string query)
{
var users = await _userService.SearchAsync(query);
var result = users.Select(u => new { u.Id, u.Username, u.Email });
return Ok(result);
}
}
}
Mobile version