Ghi
Quyền truy cập vào trang này yêu cầu sự cho phép. Bạn có thể thử đăng nhập hoặc thay đổi thư mục.
Quyền truy cập vào trang này yêu cầu sự cho phép. Bạn có thể thử thay đổi thư mục.
| Property | Value |
|---|---|
| Rule ID | CA5368 |
| Title | Set ViewStateUserKey For Classes Derived From Page |
| Category | Security |
| Fix is breaking or non-breaking | Non-breaking |
| Enabled by default in .NET 10 | No |
Cause
The Page.ViewStateUserKey property is not assigned in Page.OnInit or the Page_Init method.
Rule description
When designing an ASP.NET Web Form, be mindful of cross-site request forgery (CSRF) attacks. A CSRF attack can send malicious requests from an authenticated user to your ASP.NET Web Form.
One way of protecting against CSRF attacks in ASP.NET Web Form is by setting a page's ViewStateUserKey to a string that is unpredictable and unique to a session. For more information, see Take Advantage of ASP.NET Built-in Features to Fend Off Web Attacks.
How to fix violations
Set the ViewStateUserKey property to a unpredictable and unique string per session. For example, if you use ASP.NET session state, HttpSessionState.SessionID will work.
When to suppress warnings
It's safe to suppress a warning from this rule if:
- The ASP.NET Web Form page does not perform sensitive operations.
- Cross-site request forgery attacks are mitigated in a way that this rule doesn't detect. For example, if the page inherits from a master page that contains CSRF defenses.
Suppress a warning
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA5368
// The code that's violating the rule is on this line.
#pragma warning restore CA5368
To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA5368.severity = none
For more information, see How to suppress code analysis warnings.
Pseudo-code examples
Violation
using System;
using System.Web.UI;
class ExampleClass : Page
{
protected override void OnInit (EventArgs e)
{
}
}
Solution
using System;
using System.Web.UI;
class ExampleClass : Page
{
protected override void OnInit (EventArgs e)
{
// Assuming that your page makes use of ASP.NET session state and the SessionID is stable.
ViewStateUserKey = Session.SessionID;
}
}