All rules
CA5368Security Enabled by default: No

Set ViewStateUserKey For Classes Derived From Page

Set ViewStateUserKey For Classes Derived From Page

Microsoft docs

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 System.Web.UI.Page.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#viewstateuserkey).

Cause

The System.Web.UI.Page.ViewStateUserKey property is not assigned in System.Web.UI.Page.OnInit or the Page_Init method.

How to fix violations

Set the System.Web.UI.Page.ViewStateUserKey property to a unpredictable and unique string per session. For example, if you use ASP.NET session state, System.Web.SessionState.HttpSessionState.SessionID will work.

Example

using System;
using System.Web.UI;

class ExampleClass : Page
{
    protected override void OnInit (EventArgs e)
    {
    }
}

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;
    }
}

When to suppress

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.
Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0