위조 방지를 해결하는 방법내 ASP에서 i가 재설정된 후 발생하는 토큰 예외.넷 MVC 앱?
저는 위조방지에 문제가 있습니다ASP의 토큰.순 MVC.웹 서버에서 iisreset을 수행하고 사용자가 세션을 계속 진행하면 로그인 페이지로 튕겨집니다.끔찍하지는 않지만 위조 방지 토큰이 터지고 다시 사용할 수 있는 유일한 방법은 브라우저의 쿠키를 날려버리는 것입니다.
버전 1의 베타 버전에서는 쿠키를 다시 읽을 때 오류가 나서 검증 토큰을 요청하기 전에 스크러빙하곤 했는데 출시되었을 때 수정되었습니다.
지금은 베타 문제를 해결한 코드로 롤백할 것 같지만 뭔가를 놓치고 있다고 생각할 수밖에 없습니다.더 간단한 해결책이 있을까요? 그냥 그들의 도우미를 버리고 처음부터 새로 만들어야 하나요?문제의 많은 부분이 오래된 ASP에 너무 깊게 연결되어 있다는 사실이라는 느낌을 받습니다.네트워크 파이프라인을 구축하고 실제로는 의도하지 않은 일을 하도록 강요하고 있습니다.
ASP의 소스코드를 찾아봤습니다.Net MVC 2 RC와 코드가 많이 바뀐 것 같지 않아서 시도해보지는 않았지만 답이 없는 것 같습니다.
여기 예외의 스택 트레이스에 해당하는 부분이 있습니다.
편집: GET 요청에 토큰을 삽입하려는 것뿐이라는 것을 언급하지 않았다는 것을 방금 깨달았습니다.이것은 POST를 시작할 때 발생하는 유효성 검사가 아닙니다.
System.Web.Mvc.HttpAntiForgeryException: A required anti-forgery token was not
supplied or was invalid.
---> System.Web.HttpException: Validation of viewstate MAC failed. If this
application is hosted by a Web Farm or cluster, ensure that <machineKey>
configuration specifies the same validationKey and validation algorithm.
AutoGenerate cannot be used in a cluster.
---> System.Web.UI.ViewStateException: Invalid viewstate.
Client IP: 127.0.0.1
Port: 4991
User-Agent: scrubbed
ViewState: scrubbed
Referer: blah
Path: /oursite/Account/Login
---> System.Security.Cryptography.CryptographicException: Padding is invalid and
cannot be removed.
at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
--- End of inner exception stack trace ---
--- End of inner exception stack trace ---
at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError)
at System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState)
at System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken)
--- End of inner exception stack trace ---
at System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken)
at System.Web.Mvc.HtmlHelper.GetAntiForgeryTokenAndSetCookie(String salt, String domain, String path)
at System.Web.Mvc.HtmlHelper.AntiForgeryToken(String salt, String domain, String path)
MachineKey가 AutoGenerate로 설정되어 있으면 확인 토큰 등이 애플리케이션 재시작(ASP)에서 살아남지 못합니다.NET은 시작할 때 새 키를 생성하고 토큰을 올바르게 해독할 수 없습니다.
이것을 많이 보고 계신다면 다음과 같이 제안해 드립니다.
- 정적 시스템 키 구성(응용 프로그램 수준에서 이 작업을 수행할 수 있어야 함) 자세한 내용은 "방법: 시스템 키 구성"을 참조하십시오.
- 사이트를 사용할1 때 IIS 재설정을 수행하지 않도록 합니다.
1 가장 좋은 방법은 정적 시스템 키를 설정해야 하는 로드 밸런싱 애플리케이션을 사용하는 것입니다.다른 옵션은 다음 이름의 파일을 배치하여 사이트를 다운시키는 것입니다.app_offline.htm사이트의 루트에서 사이트를 오프라인으로 전환하고 메시지를 표시합니다. 최소한 사용자는 문제가 발생할 것으로 예상합니다.
지금은 예외적인 경우 쿠키를 스크럽하는 해결책을 가지고 있습니다.만약 다시 예외가 인정된다면 저는 그냥 원래대로 그렇게 하도록 하겠습니다.
저는 누군가가 더 나은 답을 얻기를 바라면서 이것을 '답'으로 표시하지는 않겠습니다.
public static class MyAntiForgeryExtensions
{
// Methods
public static string MyAntiForgeryToken(this HtmlHelper helper)
{
return MyAntiForgeryToken(helper, null);
}
public static string MyAntiForgeryToken(this HtmlHelper helper, string salt)
{
string fragment;
string path = helper.ViewContext.HttpContext.Request.ApplicationPath;
try
{
fragment = helper.AntiForgeryToken(salt, null, path);
}
catch (HttpAntiForgeryException)
{
// okay, scrub the cookie and have another go.
string cookieName = GetAntiForgeryTokenName(path);
helper.ViewContext.HttpContext.Request.Cookies.Remove(cookieName);
fragment = helper.AntiForgeryToken(salt, null, path);
}
return fragment;
}
#region AntiForgeryData code that shouldn't be sealed
// Copied from AntiForgeryData since they aren't accessible.
internal static string GetAntiForgeryTokenName(string appPath) {
if (String.IsNullOrEmpty(appPath)) {
return "__RequestVerificationToken";
}
else {
return "__RequestVerificationToken_" + Base64EncodeForCookieName(appPath);
}
}
private static string Base64EncodeForCookieName(string s) {
byte[] rawBytes = Encoding.UTF8.GetBytes(s);
string base64String = Convert.ToBase64String(rawBytes);
// replace base64-specific characters with characters that are safe for a cookie name
return base64String.Replace('+', '.').Replace('/', '-').Replace('=', '_');
}
#endregion
}
이 문제가 있었는데 수정하려면 웹 구성에 명시적인 기계 키를 추가해야 합니다.
<machineKey validationKey="D82960E6B6E9B9029D4CAB2F597B5B4AF631E3C182670855D25FBDE1BFAFE19EFDE92ABBD1020FC1B2AE455D5B5F8D094325597CE1A7F8B15173407199C85A16" decryptionKey="577404C3A13F154908D7A5649EEC8D7C8A92C35A25A3EC078B426BB09D426A71" validation="SHA1" decryption="AES" />
...내의 web.config에 있는지 확인합니다.
<system.web>
추가할 수 있습니다.AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;안으로global.asax
protected void Application_Start() {
AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;
}
웹 서버에서 iisreset을 수행하고 사용자가 세션을 계속 진행하면 로그인 페이지로 튕겨집니다.
사용자를 로그인 페이지로 가져올 이유가 없습니다.쿠키를 사용하여 인증 정보를 추적하고 상태 비저장 응용프로그램을 사용하는 경우 서버 재부팅 후에도 인증 상태를 유지해야 합니다(물론 재설정 중에 요청을 하면 실패함).
실제로 로그온 작업에서 사용할 수 있는 기능을 발견했습니다.
public ActionResult LogOn()
{
formsAuthentication.SignOut();
Response.Cookies.Clear();
Session[SessionKeys.USER_SESSION_KEY] = null;
Session.Clear();
Session.Abandon();
return View();
}
중요한 부분은 바로 응답입니다.쿠키.지우기();
언급URL : https://stackoverflow.com/questions/2206595/how-do-i-solve-an-antiforgerytoken-exception-that-occurs-after-an-iisreset-in-my
'programing' 카테고리의 다른 글
| Oracle이 Docker에서 작동하는지 확인하려면 어떻게 해야 합니까? (0) | 2023.11.06 |
|---|---|
| 이 오류는 무엇을 의미합니까? 'somefile.c:200: error: 1032바이트의 프레임 크기가 1024바이트보다 큽니다.' (0) | 2023.11.06 |
| 길이 또는 정수의 최대값을 정의하는 상수가 있습니까? (0) | 2023.11.06 |
| 선택 쿼리의 결과를 삽입 선택 쿼리의 매개 변수로 사용 (0) | 2023.11.06 |
| Oracle 11g에서 JSON 지원 (0) | 2023.11.06 |