Menu
CoddyTech

CORS

Thuộc phần REST API trong hành trình ASP.NET Core của Coddy. Bài học 17 trên 20.

Một trang tại https://shop.example.com gọi API của bạn bằng fetch, nhưng trình duyệt chặn phản hồi. Trình duyệt chỉ cho phép một trang đọc phản hồi từ chính origin của trang đó (giao thức, máy chủ và cổng), trừ khi máy chủ cho phép các origin khác bằng tiêu đề CORS. Trước yêu cầu PUT, PATCH, DELETE hoặc yêu cầu có phần thân JSON, trình duyệt gửi yêu cầu OPTIONS trước, gọi là preflight, rồi chỉ gửi yêu cầu thực sự nếu phản hồi cho phép.

builder.Services.AddCors(options =>
    options.AddPolicy("shop", policy => policy
        .WithOrigins("https://shop.example.com")
        .WithMethods("GET", "POST")
        .WithHeaders("Content-Type")));
var app = builder.Build();
app.UseCors("shop");

Middleware CORS phản hồi yêu cầu preflight bằng mã 204 cùng các phương thức và tiêu đề được phép, đồng thời thêm Access-Control-Allow-Origin vào mọi phản hồi dành cho origin đó. Origin khác sẽ không nhận được tiêu đề CORS, nên trình duyệt của origin đó sẽ chặn phản hồi. Chỉ trình duyệt mới áp dụng CORS: curl và thanh yêu cầu bỏ qua quy tắc này.

challenge icon

Thử thách

Trung bình

Một ứng dụng bảng trên trang khác, https://board.example.com, muốn gọi API của bạn từ trình duyệt. Chỉ cho phép origin đó.

  1. Trong Program.cs, trước builder.Build(), thêm chính sách CORS có tên board bằng builder.Services.AddCors. Chính sách này cho phép origin https://board.example.com, các phương thức GET, POST, PUT, PATCH và DELETE, cùng header Content-Type.
  2. Bảng hiển thị "page 1 of 3" từ X-Total-Count. Một trang từ origin khác chỉ đọc được một vài header phản hồi tiêu chuẩn, trừ khi máy chủ cho phép truy cập thêm header, vì vậy hãy thêm .WithExposedHeaders("X-Total-Count") vào chính sách.
  3. Sau app.UseStatusCodePages();, bật chính sách bằng app.UseCors("board");

Yêu cầu preflight từ bảng nhận phản hồi 204 cùng các header sau:

Access-Control-Allow-Origin: https://board.example.com
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE
Access-Control-Allow-Headers: Content-Type

Thử ngay: nhấn Chạy, chọn OPTIONS, đường dẫn /api/tasks/2, rồi thêm các header Origin: https://board.example.com và Access-Control-Request-Method: DELETE. Gửi yêu cầu: nhận phản hồi 204, nội dung trống và các header trên trong thẻ Headers. Gửi GET /api/tasks với cùng Origin: nhận phản hồi 200 cùng Access-Control-Allow-Origin và Access-Control-Expose-Headers. Với Origin: https://evil.example.com, phản hồi không có header CORS.

Tự làm thử

using System.ComponentModel.DataAnnotations;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();

var tasks = new List<TaskItem>
{
    new(1, "Write the project brief", false, 1),
    new(2, "Book the meeting room", true, 3),
    new(3, "Send the invoice", false),
};
var nextId = 4;

bool TitleTaken(string title, int exceptId) =>
    tasks.Any(t => t.Id != exceptId && string.Equals(t.Title, title, StringComparison.OrdinalIgnoreCase));

app.MapGet("/api/tasks", (bool? done, string? search, int? priority, string? sort, HttpResponse response, int page = 1, int pageSize = 10) =>
{
    var errors = new Dictionary<string, string[]>();
    if (sort is not null && sort != "id" && sort != "title" && sort != "priority")
        errors["sort"] = ["Sort by id, title or priority."];
    if (priority is < 1 or > 3)
        errors["priority"] = ["Priority is 1 to 3."];
    if (page < 1)
        errors["page"] = ["Page starts at 1."];
    if (pageSize < 1 || pageSize > 50)
        errors["pageSize"] = ["Page size is 1 to 50."];
    if (errors.Count > 0) return Results.ValidationProblem(errors);

    IEnumerable<TaskItem> result = tasks;
    if (done is not null) result = result.Where(t => t.Done == done);
    if (!string.IsNullOrWhiteSpace(search))
        result = result.Where(t => t.Title.Contains(search, StringComparison.OrdinalIgnoreCase));
    if (priority is not null) result = result.Where(t => t.Priority == priority);
    if (sort == "title") result = result.OrderBy(t => t.Title);
    if (sort == "priority") result = result.OrderBy(t => t.Priority);

    var matching = result.ToList();
    response.Headers["X-Total-Count"] = matching.Count.ToString();
    return Results.Ok(matching.Skip((page - 1) * pageSize).Take(pageSize));
});

app.MapGet("/api/tasks/{id:int}", (int id) =>
{
    var task = tasks.Find(t => t.Id == id);
    return task is null ? Results.NotFound() : Results.Ok(task);
});

app.MapPost("/api/tasks", (TaskInput input) =>
{
    var errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    if (TitleTaken(input.Title, 0))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    var task = new TaskItem(nextId++, input.Title, input.Done, input.Priority);
    tasks.Add(task);
    return Results.Created($"/api/tasks/{task.Id}", task);
});

app.MapPut("/api/tasks/{id:int}", (int id, TaskInput input) =>
{
    var errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    if (TitleTaken(input.Title, id))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    tasks[index] = new TaskItem(id, input.Title, input.Done, input.Priority);
    return Results.Ok(tasks[index]);
});

app.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
    var errors = Validation.Errors(patch);
    if (errors is not null) return Results.ValidationProblem(errors);
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    if (patch.Title is not null && TitleTaken(patch.Title, id))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    var task = tasks[index];
    tasks[index] = task with
    {
        Title = patch.Title ?? task.Title,
        Done = patch.Done ?? task.Done,
        Priority = patch.Priority ?? task.Priority,
    };
    return Results.Ok(tasks[index]);
});

app.MapDelete("/api/tasks/{id:int}", (int id) =>
{
    var removed = tasks.RemoveAll(t => t.Id == id);
    return removed == 0 ? Results.NotFound() : Results.NoContent();
});

app.MapDelete("/api/tasks", (bool? done) =>
{
    if (done != true)
    {
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            ["done"] = ["Add ?done=true to delete the done tasks."],
        });
    }
    tasks.RemoveAll(t => t.Done);
    return Results.NoContent();
});

app.Run();

record TaskItem(int Id, string Title, bool Done, int Priority = 2);
record TaskInput(
    [property: Required(ErrorMessage = "Title is required."), StringLength(80)] string Title,
    bool Done,
    [property: Range(1, 3)] int Priority = 2);
record TaskPatch(string? Title, bool? Done, [property: Range(1, 3)] int? Priority);
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong REST API