在ASP.NET Core中使用防伪并得到错误-无法解密防伪令牌 [英] Using Antiforgery in ASP.NET Core and got error - the antiforgery token could not be decrypted

查看:104
本文介绍了在ASP.NET Core中使用防伪并得到错误-无法解密防伪令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ASP.Net Core MVC应用程序已添加 Antiforgery 中间件,如下所示:

My ASP.Net Core MVC application have added Antiforgery middleware like below:

startup.cs

services.AddMvc();
services.AddSession();
services.AddCaching();
services.AddSession(o =>
{
  o.IdleTimeout = TimeSpan.FromMinutes(120);
});
services.AddAntiforgery();

我在下面的视图和控制器中添加了

I've added below in the view and controller

查看:

<form action="/Home/Login" method="post" id="staff-login" autocomplete="off">

@Html.AntiForgeryToken()

 ......

控制器

[HttpPost, ValidateAntiForgeryToken] 
public IActionResult Login(IFormCollection formCollection) 
{...}

问题在于,当用户遇到不同的表单时,用户总是会跌倒.

The problem is users always get below when users come across different forms.

System.InvalidOperationException:防伪令牌不能为 解密. ---> System.Security.Cryptography.CryptographicException: 找不到密钥{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} 钥匙圈.

System.InvalidOperationException: The antiforgery token could not be decrypted. ---> System.Security.Cryptography.CryptographicException: The key {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} was not found in the key ring.

我找到了一个解决方案,建议在web.config中设置一对静态的验证/解密密钥,但是看来该解决方案仅适用于经典的asp.net应用程序.我应该如何在ASP.Net core中做什么?

I found a solution which suggests setting a static pair of validation/decryption key in the web.config but it seems this solution is only for classic asp.net application. How should I do in ASP.Net core?

推荐答案

在Linux容器上托管的ASP .net核心应用程序中,我确实遇到了该错误.

I've had exactly that error on a ASP .net core app hosted on a linux container.

来自文档看来,如果您不符合某些条件,则密钥只会保留在该过程中-但是即使对于我来说,它也不起作用.

From the docs it would seem if you don't meet certain criteria the keys are only persisted in the process - but that even for me was not working.

首先,使用默认设置发生了错误.
然后,我为文件系统上的键添加了特定的配置:

First the error occurred with the default setup.
I then added specific configuration for the keys on the filesystem:

            services.AddDataProtection()
                .PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"/var/my-af-keys/"));

这也不能解决我必须设置应用程序名称的问题:

This also didn't fix the issue I had to set an application name:

            services.AddDataProtection()
                .SetApplicationName("fow-customer-portal")
                .PersistKeysToFileSystem(new System.IO.DirectoryInfo(@"/var/dpkeys/"));

我尚未确认,但LXC托管的可能性质意味着.net核心无法保留该应用程序的身份.

I haven't confirmed but its possible nature of the LXC hosting means .net core cannot persist the identity of the app.

这篇关于在ASP.NET Core中使用防伪并得到错误-无法解密防伪令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆