如何在.net8中创建CSRF令牌

问题描述 投票:0回答:1

我尝试将文件发送到服务器。虽然发布 json 非常简单,但通过 API 发送 excel 文件(上传 xlsx 文件到服务器)时我遇到了很多麻烦。

服务器端代码

    app.MapPost("/uploadexlsx", async (IFormFile file) =>
    {
    List<string> validextensions = new List<string>() { ".xlsx" };
    string extension = Path.GetExtension(file.FileName);
    if (!validextensions.Contains(extension))
    {
        return $"Extention is not valid({string.Join(",", validextensions)})";
    }
    string filename = "File1" + extension;
    string path = @"D:/";
    try
    {
        using FileStream stream = new FileStream(Path.Combine(path, filename), FileMode.Create);
        await file.CopyToAsync(stream);
        return filename;
    }
    catch (Exception ex)
    {
        // Log the exception or return an appropriate error response
        return $"Error uploading file: {ex.Message}";
    }
    });

客户端:

    public async Task SendExcelFileToServer(string filepath , string filename , string   InnerAddress)
    {
    try
    {
        // Create an instance of HttpClient
        using (var httpClient = new HttpClient())
        {
            // Set the request URI
            string requestUri = ServerAddressTextBox.Text.Trim() + InnerAddress;

            // Create multipart form data content
            using (var form = new MultipartFormDataContent())
            {
                // Add file part
                using (var fileContent = new ByteArrayContent(File.ReadAllBytes(filepath)))
                {
                    fileContent.Headers.ContentType =   
                       MediaTypeHeaderValue.Parse("application/vnd.openxmlformats-
                          officedocument.spreadsheetml.sheet");
                    form.Add(fileContent, "file", filename);
                }

                // Send post request
                HttpResponseMessage response = await httpClient.PostAsync(requestUri, form);

                // Check response
                response.EnsureSuccessStatusCode();
            }
        }

    }
    catch
    {
        MessageBox.Show("Try sending data again and check your connection!");
    }
    }

根据api对邮递员Postrequest的响应:

” `System.InvalidOperationException:端点 HTTP:POST /upload2 包含防伪元数据,但未找到支持防伪的中间件。 通过在应用程序启动代码中添加 app.UseAntiforgery() 来配置应用程序启动。如果存在对 app.UseRouting() 和 app.UseEndpoints(...) 的调用,则对 app.UseAntiforgery() 的调用必须在它们之间进行。对 app.UseAntiforgery() 的调用必须在对 app.UseAuthentication() 和 app.UseAuthorization() 的调用之后进行。 在 Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingAntiforgeryMiddlewareException(端点端点) 在 Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext 上下文)

标题

Accept: */*
Host: 26f2-51-81-84-47.ngrok-free.app
User-Agent: PostmanRuntime/7.38.0
Accept-Encoding: gzip, deflate, br
Content-Type: multipart/form-data; boundary=--------------------------085075967638336328741999
Content-Length: 11245
Postman-Token: da76f52f-4c8d-4430-8834-b4ed5fb65ef9
X-Forwarded-For: 51.81.84.47
X-Forwarded-Host: 26f2-51-81-84-47.ngrok-free.app
X-Forwarded-Proto: https
`
"

看来我必须将 CSRF 令牌添加到我的文件中。我认为这是.net8中必须的! (这是一件好事!!!但是,它正在杀了我)

我不知道如何在服务器端创建此令牌。

我在chatgpt上找到了这个,但似乎GetAndValidateRequestTokenAsync不存在:

    app.MapGet("/GetToken", async (IAntiforgery antiforgery) =>
    {
    var token = await antiforgery.GetAndValidateRequestTokenAsync(HttpContext);
    return token;
    });

我应该如何创建这个令牌以及如何将其添加到客户端的文件流中?

c# asp.net-core .net-8.0
1个回答
0
投票

如果您想在 minial-api 中生成 CSRF 令牌,我建议您可以按照以下示例操作:

1.添加防伪服务并在程序内启用.cs:

...
builder.Services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
var app = builder.Build();
app.UseAntiforgery();
...

2.添加token生成api:

app.MapGet("/gettoken", (HttpContext context, IAntiforgery antiforgery) =>
{
    var token = antiforgery.GetAndStoreTokens(context);
    return Results.Content(token.RequestToken );
});

请求头: enter image description here

邮递员本体:

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.