Ich deklariere Einstellungen für die Sitzung
Code: Select all
builder.Services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
Code: Select all
builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"./keys"))
.UseCryptographicAlgorithms(new AuthenticatedEncryptorConfiguration {
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
})
.SetApplicationName("BudgetTracker")
.SetDefaultKeyLifetime(TimeSpan.FromDays(14));
Code: Select all
builder.Services.AddControllersWithViews(options => {
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
Code: Select all
builder.Services.AddAntiforgery(options => {
options.HeaderName = "X-XSRF-TOKEN";
options.Cookie.Name = "XSRF-TOKEN";
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.HttpOnly = false;
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.Expiration = TimeSpan.FromDays(14);
options.SuppressXFrameOptionsHeader = false;
options.FormFieldName = "AntiforgeryField";
});
Code: Select all
app.UseMiddleware();
Code: Select all
public class AntiForgeryMiddleware {
private readonly IAntiforgery _antiforgery;
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public AntiForgeryMiddleware(RequestDelegate next, IAntiforgery antiforgery, ILogger logger) {
_next = next;
_antiforgery = antiforgery;
_logger = logger;
}
public async Task Invoke(HttpContext context) {
try {
if (string.Equals(context.Request.Path.Value, "/session/csrf", StringComparison.OrdinalIgnoreCase)) {
var token = _antiforgery.GetAndStoreTokens(context).RequestToken;
if (!string.IsNullOrEmpty(token)) {
context.Response.Cookies.Append("XSRF-TOKEN", token, new CookieOptions {
HttpOnly = false,
Secure = true,
SameSite = SameSiteMode.None,
Expires = DateTimeOffset.UtcNow.AddDays(14)
});
}
_logger.LogInformation($"Generated XSRF-TOKEN: {token}");
}
} catch (Exception ex) {
_logger.LogError(new EventId(), ex, ex.Message);
throw;
}
await _next(context);
}
}
Code: Select all
intercept(request: HttpRequest\, next: HttpHandler): Observable\ {
let token = this.tokenExtractor.getToken();
let permitted = this.findByActionName(request.method, this.actions);
let forbidden = this.findByActionName(request.method, this.forbiddenActions);;
if (permitted !== undefined && forbidden === undefined && token !== null) {
request = request.clone({ setHeaders: { "X-XSRF-TOKEN": token }, withCredentials: true });
}
return next.handle(request);
}
private findByActionName(name: string, actions: string\[\]): string | undefined {
return actions.find(action =\> action.toLocaleLowerCase() === name.toLocaleLowerCase());
}
}
Code: Select all
info: webapi.Middlewares.AntiForgeryTokenLoggingMiddleware[0]
Request XSRF-TOKEN: cece034d-b5a2-4042-a884-c4aa9399436b
info: webapi.Middlewares.AntiForgeryTokenLoggingMiddleware[0]
Request X-XSRF-TOKEN: cece034d-b5a2-4042-a884-c4aa9399436b
Code: Select all
[19:02:46 INF] Antiforgery token validation failed. The antiforgery token could not be decrypted.
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.
---> System.Security.Cryptography.CryptographicException: The provided payload cannot be decrypted because it was not protected with this protection provider.
Danke!