Skip to content

Commit 3435fc4

Browse files
add antiforgery header when uploading document (Azure-Samples#204)
## 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. -->
1 parent 092e1db commit 3435fc4

File tree

5 files changed

+35
-2
lines changed

5 files changed

+35
-2
lines changed

app/backend/Program.cs

+12
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Copyright (c) Microsoft. All rights reserved.
22

3+
using Microsoft.AspNetCore.Antiforgery;
4+
35
var builder = WebApplication.CreateBuilder(args);
46

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

1619
if (builder.Environment.IsDevelopment())
1720
{
@@ -80,8 +83,17 @@
8083
app.UseStaticFiles();
8184
app.UseCors();
8285
app.UseBlazorFrameworkFiles();
86+
app.UseAntiforgery();
8387
app.MapRazorPages();
8488
app.MapControllers();
89+
90+
app.Use(next => context =>
91+
{
92+
var antiforgery = app.Services.GetRequiredService<IAntiforgery>();
93+
var tokens = antiforgery.GetAndStoreTokens(context);
94+
context.Response.Cookies.Append("XSRF-TOKEN", tokens?.RequestToken ?? string.Empty, new CookieOptions() { HttpOnly = false });
95+
return next(context);
96+
});
8597
app.MapFallbackToFile("index.html");
8698

8799
app.MapApi();

app/frontend/Pages/Docs.razor.cs

+6-1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@ public sealed partial class Docs : IDisposable
2828
[Inject]
2929
public required ILogger<Docs> Logger { get; set; }
3030

31+
[Inject]
32+
public required IJSRuntime JSRuntime { get; set; }
33+
3134
private bool FilesSelected => _fileUpload is { Files.Count: > 0 };
3235

3336
protected override void OnInitialized() =>
@@ -64,8 +67,10 @@ private async Task SubmitFilesForUploadAsync()
6467
{
6568
if (_fileUpload is { Files.Count: > 0 })
6669
{
70+
var cookie = await JSRuntime.InvokeAsync<string>("getCookie", "XSRF-TOKEN");
71+
6772
var result = await Client.UploadDocumentsAsync(
68-
_fileUpload.Files, MaxIndividualFileSize);
73+
_fileUpload.Files, MaxIndividualFileSize, cookie);
6974

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

app/frontend/Services/ApiClient.cs

+6-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ public async Task<bool> ShowLogoutButtonAsync()
2626

2727
public async Task<UploadDocumentsResponse> UploadDocumentsAsync(
2828
IReadOnlyList<IBrowserFile> files,
29-
long maxAllowedSize)
29+
long maxAllowedSize,
30+
string cookie)
3031
{
3132
try
3233
{
@@ -42,6 +43,10 @@ public async Task<UploadDocumentsResponse> UploadDocumentsAsync(
4243
content.Add(fileContent, file.Name, file.Name);
4344
}
4445

46+
// set cookie
47+
content.Headers.Add("X-CSRF-TOKEN-FORM", cookie);
48+
content.Headers.Add("X-CSRF-TOKEN-HEADER", cookie);
49+
4550
var response = await httpClient.PostAsync("api/documents", content);
4651

4752
response.EnsureSuccessStatusCode();

app/frontend/wwwroot/getCookie.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
function getCookie(cname) {
2+
var decodedCookie = decodeURIComponent(document.cookie);
3+
var ca = decodedCookie.split(';');
4+
for (var i = 0; i < ca.length; i++) {
5+
var arr = ca[i].split('=');
6+
if (arr[0] == cname)
7+
return arr[1]
8+
}
9+
return "";
10+
}

app/frontend/wwwroot/index.html

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
<script>navigator.serviceWorker.register('service-worker.js');</script>
3636
<script src="_content/MudBlazor/MudBlazor.min.js"></script>
3737
<script src="_content/Blazor.SpeechSynthesis.WebAssembly/blazorators.speechSynthesis.g.js"></script>
38+
<script src="getCookie.js"></script>
3839
<script src="https://cdn.jsdelivr.net/gh/highlightjs/[email protected]/build/highlight.min.js"></script>
3940
<script src="https://cdn.jsdelivr.net/gh/highlightjs/[email protected]/build/languages/csharp.min.js" defer></script>
4041
<script src="https://cdn.jsdelivr.net/gh/highlightjs/[email protected]/build/languages/dockerfile.min.js" defer></script>

0 commit comments

Comments
 (0)