Skip to content

Commit

Permalink
add antiforgery header when uploading document (#204)
Browse files Browse the repository at this point in the history
## Purpose
<!-- Describe the intention of the changes being proposed. What problem
does it solve or functionality does it add? -->
* ...

## Does this introduce a breaking change?
<!-- Mark one with an "x". -->
```
[ ] Yes
[ ] No
```

## Pull Request Type
What kind of change does this Pull Request introduce?

<!-- Please check the one that applies to this PR using "x". -->
```
[ ] Bugfix
[ ] Feature
[ ] Code style update (formatting, local variables)
[ ] Refactoring (no functional changes, no api changes)
[ ] Documentation content changes
[ ] Other... Please describe:
```

## How to Test
*  Get the code

```
git clone [repo-address]
cd [repo-name]
git checkout [branch-name]
npm install
```

* Test the code
<!-- Add steps to run the tests suite and/or manually test -->
```
```

## What to Check
Verify that the following are valid
* ...

## Other Information
<!-- Add any other helpful information that may be needed here. -->
  • Loading branch information
LittleLittleCloud authored Oct 26, 2023
1 parent 092e1db commit 3435fc4
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 2 deletions.
12 changes: 12 additions & 0 deletions app/backend/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.

using Microsoft.AspNetCore.Antiforgery;

var builder = WebApplication.CreateBuilder(args);

builder.Configuration.ConfigureAzureKeyVault();
Expand All @@ -12,6 +14,7 @@
builder.Services.AddRazorPages();
builder.Services.AddCrossOriginResourceSharing();
builder.Services.AddAzureServices();
builder.Services.AddAntiforgery(options => { options.HeaderName = "X-CSRF-TOKEN-HEADER"; options.FormFieldName = "X-CSRF-TOKEN-FORM"; });

if (builder.Environment.IsDevelopment())
{
Expand Down Expand Up @@ -80,8 +83,17 @@
app.UseStaticFiles();
app.UseCors();
app.UseBlazorFrameworkFiles();
app.UseAntiforgery();
app.MapRazorPages();
app.MapControllers();

app.Use(next => context =>
{
var antiforgery = app.Services.GetRequiredService<IAntiforgery>();
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens?.RequestToken ?? string.Empty, new CookieOptions() { HttpOnly = false });
return next(context);
});
app.MapFallbackToFile("index.html");

app.MapApi();
Expand Down
7 changes: 6 additions & 1 deletion app/frontend/Pages/Docs.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ public sealed partial class Docs : IDisposable
[Inject]
public required ILogger<Docs> Logger { get; set; }

[Inject]
public required IJSRuntime JSRuntime { get; set; }

private bool FilesSelected => _fileUpload is { Files.Count: > 0 };

protected override void OnInitialized() =>
Expand Down Expand Up @@ -64,8 +67,10 @@ private async Task SubmitFilesForUploadAsync()
{
if (_fileUpload is { Files.Count: > 0 })
{
var cookie = await JSRuntime.InvokeAsync<string>("getCookie", "XSRF-TOKEN");

var result = await Client.UploadDocumentsAsync(
_fileUpload.Files, MaxIndividualFileSize);
_fileUpload.Files, MaxIndividualFileSize, cookie);

Logger.LogInformation("Result: {x}", result);

Expand Down
7 changes: 6 additions & 1 deletion app/frontend/Services/ApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ public async Task<bool> ShowLogoutButtonAsync()

public async Task<UploadDocumentsResponse> UploadDocumentsAsync(
IReadOnlyList<IBrowserFile> files,
long maxAllowedSize)
long maxAllowedSize,
string cookie)
{
try
{
Expand All @@ -42,6 +43,10 @@ public async Task<UploadDocumentsResponse> UploadDocumentsAsync(
content.Add(fileContent, file.Name, file.Name);
}

// set cookie
content.Headers.Add("X-CSRF-TOKEN-FORM", cookie);
content.Headers.Add("X-CSRF-TOKEN-HEADER", cookie);

var response = await httpClient.PostAsync("api/documents", content);

response.EnsureSuccessStatusCode();
Expand Down
10 changes: 10 additions & 0 deletions app/frontend/wwwroot/getCookie.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function getCookie(cname) {
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var arr = ca[i].split('=');
if (arr[0] == cname)
return arr[1]
}
return "";
}
1 change: 1 addition & 0 deletions app/frontend/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
<script>navigator.serviceWorker.register('service-worker.js');</script>
<script src="_content/MudBlazor/MudBlazor.min.js"></script>
<script src="_content/Blazor.SpeechSynthesis.WebAssembly/blazorators.speechSynthesis.g.js"></script>
<script src="getCookie.js"></script>
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.7.0/build/highlight.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.7.0/build/languages/csharp.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.7.0/build/languages/dockerfile.min.js" defer></script>
Expand Down

0 comments on commit 3435fc4

Please sign in to comment.