Cấp bậc tác giả:

DOTNET

Làm sao để chỉ cho phép một số role truy cập truy vấn $expand=SensitiveData?

Được viết bởi webmaster ngày 05/06/2025 lúc 10:54 AM
Để chỉ cho phép một số role truy cập $expand=SensitiveData trong OData, bạn cần kiểm tra quyền (role-based access) tại thời điểm middleware hoặc trong controller khi xử lý $expand.
  • 0
  • 40

Làm sao để chỉ cho phép một số role truy cập truy vấn $expand=SensitiveData?

Cách làm tổng quát

  1. Xác định user và role (qua Claims/Identity).

  2. Phân tích truy vấn $expand trong request.

  3. Nếu có $expand=SensitiveData → kiểm tra quyền.

  4. Nếu không đủ quyền → trả về 403 Forbidden.

Ví dụ triển khai trong ASP.NET Core OData (OData v8)

🔸 1. Cấu hình authentication + role-based authorization

Trong Startup.cs hoặc Program.cs:

builder.Services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options => {
        options.Authority = "https://your-auth-provider";
        options.Audience = "your-api";
    });

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("CanViewSensitiveData", policy =>
        policy.RequireRole("Admin", "Manager"));
});
🔸 2. Trong Controller – kiểm tra $expand

[EnableQuery]
public IActionResult Get()
{
    var queryOptions = HttpContext.ODataFeature().QueryOptions;
    var expandClause = queryOptions?.SelectExpand?.RawExpand;

    if (!string.IsNullOrEmpty(expandClause) && expandClause.Contains("SensitiveData", StringComparison.OrdinalIgnoreCase))
    {
        var user = HttpContext.User;
        if (!user.IsInRole("Admin") && !user.IsInRole("Manager"))
        {
            return Forbid("You are not allowed to access SensitiveData.");
        }
    }

    return Ok(_dbContext.Customers);
}

Tùy chọn: Tạo Middleware kiểm tra $expand sớm

Nếu bạn muốn áp dụng global:

public class ODataExpandSecurityMiddleware
{
    private readonly RequestDelegate _next;

    public ODataExpandSecurityMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var expand = context.Request.Query["$expand"].ToString();
        if (!string.IsNullOrEmpty(expand) && expand.Contains("SensitiveData"))
        {
            var user = context.User;
            if (!user.IsInRole("Admin") && !user.IsInRole("Manager"))
            {
                context.Response.StatusCode = StatusCodes.Status403Forbidden;
                await context.Response.WriteAsync("You are not authorized to expand SensitiveData.");
                return;
            }
        }

        await _next(context);
    }
}

Gợi ý nâng cao:

  • Có thể dùng ODataQueryOptions để phân tích sâu hơn $expand.

  • Dùng attribute [Authorize(Policy = "...")] kết hợp xử lý thủ công trong controller nếu $expand cần tùy biến theo nội dung.

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML