Sau mot buoi noi chuyen ve su khac nhau giua SSE va SignalR, cung cach trien khai thong diep huong den tung nguoi dung trong ca hai cong cu, toi nhan duoc mot cau hoi rat quan trong ma chua de cap trong buoi trinh bay: “SSE co the duoc xac thuc khong? No co ho tro header Authorization khong?”.
Vi SSE chi la mot cach truyen su kien den client thong qua mot yeu cau HTTP thong thuong, cau tra loi ngan gon la co. Cau tra loi day du hon phu thuoc vao client hoac API ma ban su dung. Trong bai viet nay, toi se giai thich cac cach khac nhau de dung SSE voi nguoi dung da xac thuc, cac bay thuong gap va cach tranh chung.
Trong vi du da chia se o buoi trinh bay, toi dung EventSource de ket noi den endpoint SSE. Van de la EventSource khong ho tro gui header. Vay cac lua chon thay the la gi? Lam the nao de xac thuc client khi dung EventSource?
Mục lục
Cookie
Diem tot la EventSource tu dong gui cookie khi ket noi den endpoint SSE, mien la cac quy tac cookie va bao mat cua trinh duyet cho phep.
Cung origin
Neu ung dung client va API nam tren cung mot origin, dong thoi trinh duyet da co cookie xac thuc, cookie do se tu dong duoc dua vao yeu cau SSE.
O phia server, endpoint ASP.NET Core co the dung middleware xac thuc thong thuong. Diem quan trong la SSE khong bo qua middleware xac thuc. Chi can cau hinh endpoint yeu cau client da duoc cap quyen, vi du dung .RequireAuthorization trong Minimal API, la du.
Khac origin
Neu ung dung client va API khong nam tren cung mot origin, vi du:
- Front-end: https://app.example.com
- Back-end: https://api.example.com
Ban can yeu cau EventSource gui kem thong tin xac thuc bang withCredentials: true:
const events = new EventSource("https://api.example.com/api/events", {
withCredentials: true,
});
Cookie cung phai hop le voi mien cua API.
Dong thoi, ban can cho phep credentials trong cau hinh CORS cua server:
builder.Services.AddCors(options =>
{
options.AddPolicy("frontend", policy =>
{
policy
.WithOrigins("https://app.example.com")
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Luu y quan trong: Khong duoc dung AllowAnyOrigin cung voi AllowCredentials().
Token ngan han
Bo canh
Truoc khi giai thich token ngan han la gi va vi sao nen dung, hay xem qua mo hinh minh hoa. Chung ta se co mot ung dung Aspire moi tao voi hai project va mot thanh phan tich hop:
- Project back-end
- Project front-end
- Thanh phan Keycloak
Trien khai
Neu khong dung cookie thi co the lam gi?
Trong truong hop nay, chung ta co the dung token ngan han. Day la token co the yeu cau tu server va chi hop le trong mot khoang thoi gian rat ngan. Dieu nay giup ich gi? Du EventSource khong ho tro header, chung ta van co the truyen tham so truy van.
Truyen access token truc tiep trong URL khong an toan. Token co the bi ghi log o dau do va lo qua log cua server hoac proxy. Chung ta khong muon dieu do xay ra.
Chung ta se trien khai mot endpoint de nguoi dung da xac thuc yeu cau token ngan han. Sau do, token ngan han nay, goi tat la SLT, se duoc truyen lam tham so truy van den endpoint SSE. Ngay ca khi bi ghi log, token cung khong con hoat dong sau mot khoang thoi gian rat ngan va chi duoc dung mot lan. Day la diem quan trong nhat.
Truoc tien, hay trien khai bo luu token trong bo nho:
public class ShortLivedTokenStore
{
private readonly ConcurrentDictionary<string, string> _tokenStore = [];
private readonly TimeSpan _lifeTime = TimeSpan.FromSeconds(10);
public string GetToken(string userId)
{
var token = Guid.NewGuid().ToString();
_tokenStore.TryAdd(token, userId);
_ = Task.Run(async () =>
{
await Task.Delay(_lifeTime);
_tokenStore.TryRemove(token, out _);
});
return token;
}
public bool TryConsume(string token, [NotNullWhen(true)] out string? userId) => _tokenStore.TryRemove(token, out userId);
}
ShortLivedTokenStore nen duoc dang ky vao services voi vong doi singleton.
Muc dich cua lop nay la tao mot bo luu token ngan han trong bo nho. Token duoc luu trong mot tu dien cung voi ID nguoi dung. Vi du nay khong su dung ID, nhung viec luu no cho thay moi token duoc gan voi mot nguoi dung.
Sau khi tao token, chung ta them token vao tu dien va chay mot tac vu de lam token het han sau 10 giay.
Cuoi cung, TryConsume kiem tra token co ton tai trong bo luu hay khong, dong thoi xoa token de no het han va tra ve userId de su dung. Trong vi du nay, chung ta bo qua gia tri do.
Luu y quan trong: Guid.NewGuid() van hoat dong, nhung khong duoc khuyen nghi cho token bao mat. Khong dung cach nay trong moi truong that. Thay vao do, co the dung RandomNumberGenerator.GetBytes(32) va ma hoa ket qua bang Base64Url.
Trong moi truong that, tot hon het la khong dung bo luu trong bo nho cho cac SLT. Cach nay khong mo rong duoc qua nhieu instance va token se mat khi ung dung khoi dong lai. Ban co the dung Redis hoac IDistributedCache.
Tiep theo, chung ta dung mot endpoint de nguoi dung da xac thuc yeu cau token ngan han:
app.MapGet("/request-slt", (HttpContext context, ShortLivedTokenStore store) =>
{
string? userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrWhiteSpace(userId))
{
return Results.Unauthorized();
}
return Results.Ok(store.GetToken(userId));
})
.WithName("RequestShortLivedToken")
.RequireAuthorization();
Endpoint nay yeu cau nguoi dung da xac thuc, vi vay khong phai ai cung co the yeu cau token ngan han. Endpoint se goi bo luu token da duoc inject de yeu cau mot token.
Sau do, chung ta cong bo mot endpoint nhan SLT de xac thuc va truyen su kien:
app.MapGet("/events-slt", (string shortLivedToken, ShortLivedTokenStore store, CancellationToken cancellationToken) =>
{
if (!store.TryConsume(shortLivedToken, out _))
{
return Results.Unauthorized();
}
int count = 0;
async IAsyncEnumerable<int> StreamEvents([EnumeratorCancellation] CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
yield return count++;
try
{
await Task.Delay(1000, ct);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
yield break;
}
}
}
return Results.ServerSentEvents(StreamEvents(cancellationToken));
}).WithName("GetEventsWithShortLivedToken");
Endpoint nay nhan token ngan han tu tham so truy van va kiem tra token trong bo luu. Neu khong tim thay token, endpoint tra ve ket qua khong duoc cap quyen. Neu hop le, endpoint bat dau truyen su kien ve client.
Luu y quan trong: EventSource tu dong ket noi lai den cung URL sau khi mang bi gian doan. Trong truong hop nay, lan ket noi lai se nhan loi 401 va dong vinh vien. Client can yeu cau mot SLT moi va tao mot EventSource moi.
File JS ma client su dung trong truong hop nay:
const connections = {};
export function connect(
id,
url,
dotNetObject,
messageCallback,
errorCallback,
shortLivedToken,
) {
disconnect(id);
const source = new EventSource(
`${url}?shortLivedToken=${encodeURIComponent(shortLivedToken)}`,
);
source.onmessage = (event) => {
dotNetObject.invokeMethodAsync(messageCallback, id, event.data);
};
source.onerror = () => {
dotNetObject.invokeMethodAsync(
errorCallback,
id,
`Connection failed or was closed for ${url}.`,
);
disconnect(id);
};
connections[id] = source;
}
export function disconnect(id) {
const source = connections[id];
if (!source) {
return;
}
source.close();
delete connections[id];
}
Su dung @microsoft/fetch-event-source
Neu khong muon trien khai them mot lop de yeu cau token ngan han, ban co the dung thu vien @microsoft/fetch-event-source. Thu vien nay dung API fetch() de xu ly SSE, cho phep ban gui header xac thuc.
Trong ung dung Blazor, co the trien khai bang JavaScript:
import { fetchEventSource } from "https://cdn.jsdelivr.net/npm/@microsoft/fetch-event-source@2.0.1/+esm";
const connections = {};
export async function connect(
id,
url,
dotNetObject,
messageCallback,
errorCallback,
token,
) {
disconnect(id);
const controller = new AbortController();
connections[id] = controller;
try {
await fetchEventSource(url, {
headers: {
Authorization: `Bearer ${token}`,
},
signal: controller.signal,
onmessage(event) {
dotNetObject.invokeMethodAsync(messageCallback, id, event.data);
},
onerror() {
dotNetObject.invokeMethodAsync(
errorCallback,
id,
`Connection failed or was closed for ${url}.`,
);
controller.abort();
},
});
} finally {
if (connections[id] === controller) {
delete connections[id];
}
}
}
export function disconnect(id) {
const controller = connections[id];
if (!controller) {
return;
}
controller.abort();
delete connections[id];
}
Sau do, ung dung Blazor co the goi ham JS nay va gui kem header authorization.
HttpClient
Cuoi cung, trong he sinh thai .NET, chung ta co the dung HttpClient de goi endpoint SSE va gui kem header authorization.
Mot cach trien khai don gian co the nhu sau:
public static class SimpleSse
{
public static async IAsyncEnumerable<string> StreamAsync(
HttpClient httpClient,
string endpoint,
string? bearerToken = null,
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
{
using var request = new HttpRequestMessage(HttpMethod.Get, endpoint);
request.Headers.TryAddWithoutValidation("Accept", "text/event-stream");
if (!string.IsNullOrWhiteSpace(bearerToken))
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearerToken);
using var response = await httpClient.SendAsync(
request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
using var reader = new StreamReader(stream);
while (await reader.ReadLineAsync(cancellationToken) is { } line)
if (line.StartsWith("data:", StringComparison.Ordinal))
yield return line.Length > 5 && line[5] == ' ' ? line[6..] : line[5..];
}
}
Ham nay tra du lieu duoi dang chuoi de ben goi co the giai ma thanh doi tuong.
Neu can mot trien khai day du, hay xem thu vien dotnet-sse-client cua toi. Co the cai dat thu vien bang lenh:
dotnet add package DotNetSseClient
De thu tung cach xac thuc SSE, ban co the lay ma nguon tu kho ma demo tren GitHub, khoi chay ung dung Aspire va mo cac muc khac nhau trong ung dung web de xem tung cach hoat dong. Ung dung co nam trang, moi trang tuong ung voi mot cach duoc giai thich trong bai viet.
Luu y rang ma demo nay su dung thu vien DotNetSseClient da de cap o tren.
Ban nen dung cach xac thuc nao?
Tat ca cac cach duoi day deu hoat dong. Lua chon phu hop phu thuoc vao client va viec ban da co cookie hay bearer token hay chua.
So sanh
| Cach tiep can | Client | Header tuy chinh? | Thay doi phia server | Cach ket noi lai | Diem can luu y |
|---|---|---|---|---|---|
| Cookie, cung origin | EventSource |
Khong can | Khong co thay doi ngoai xac thuc thong thuong | Tu dong ket noi lai tu nhien | Can xac thuc bang cookie |
| Cookie, khac origin | EventSource voi withCredentials: true |
Khong can | CORS phai co AllowCredentials() va origin cu the |
Tu dong ket noi lai tu nhien | Quy tac SameSite va viec chan cookie ben thu ba |
| Token ngan han, SLT | EventSource |
Khong, token nam trong chuoi truy van | Can endpoint cap token, bo luu token va logic kiem tra tai endpoint SSE | Bi gian doan voi token chi dung mot lan; client phai yeu cau SLT moi va tao EventSource moi |
Token co the xuat hien trong URL va log, vi vay phai co thoi han ngan va chi dung mot lan |
| fetch-event-source | Thu vien JavaScript @microsoft/fetch-event-source |
Co | CORS phai cho phep header Authorization |
Ban kiem soat qua onerror, nhung cac lan thu lai dung token ban dau |
Se thu lai vo han neu onerror khong nem loi; mac dinh dong khi tab bi an |
| HttpClient | Ma .NET | Co | Khong co | Ban tu viet logic thu lai | Phan tich du lieu co ban neu khong dung thu vien |
Toi nen dung cach nao?
- Client cua ban la ma .NET, vi du MAUI, ung dung desktop, ung dung console hoac mot service khac? Hay dung
HttpClient, tot nhat la ket hop voiSystem.Net.ServerSentEventshoac thu vienDotNetSseClient. - Client la trinh duyet va ban da dung xac thuc bang cookie hoac BFF? Hay dung cookie. Cung origin la lua chon don gian nhat. Khac origin cung hoat dong neu CORS duoc cau hinh dung.
- Client la trinh duyet, dang dung bearer token, Keycloak hoac JWT, va khong co cookie?
- Neu co the them thu vien, hay dung fetch-event-source. Cach nay khong can them endpoint phia server va khong dua token vao URL.
- Neu bat buoc dung
EventSourcegoc, hay dung token ngan han.
Khuyen nghi mac dinh
- Dung cookie neu ban da co cookie.
- Dung fetch-event-source cho bearer token trong trinh duyet.
- Chi dung token ngan han khi bat buoc phai dung
EventSourcegoc. - Dung
HttpClientcho moi truong khong phai trinh duyet.
So do tham khao nhanh

Day co phai la quy tac bat buoc khong?
Khong. Ban nen chon cach phu hop voi ngan xep cong nghe va mien nghiep vu cua minh. Vi du, Blazor co the dung ca nam cach tiep can neu tren. Quyet dinh cuoi cung phu thuoc vao nhung gi ban co the hoac khong the su dung.
Loi ket
Tren day la cac cach khac nhau de dung xac thuc voi endpoint Server-Sent Events. Ban cung co the ket hop cac cach nay voi bai viet truoc ve viec huong thong diep den nguoi dung.
Tu khoa: server-sent-events, sse, authentication, short-lived-tokens, cookies, aspnetcore, dotnet, blazor, cors, security, httpclient
Neu ban thay bai viet huu ich, hay tham gia cong dong lap trinh vien tren Discord de dat cau hoi, chia se y tuong va thao luan ve .NET cung ky thuat phan mem. Tham gia may chu Discord.



