CSRF Token - Asp.net Client - MVC Server Side [duplicate] - c#

I have a .NET Webforms site thanks needs to post to my MVC Application which currently sits inside the Webform site as a separate application.
The Webform application need to POST some sensitive values to the MVC Application.
Is there a way to generate a AntiForgeryToken() in my WebForms Application so it can be passed with the form post.
Otherwise does anyone know of any other custom anti forgery code that will allow me to do something similar to the MVC's AntiForgeryValidation.

Implementing it yourself is not too difficult.
Generate a GUID
Put it in a hidden field
Also put it in Session or Cookie (in the latter case, with some anti-tamper protection)
At the start of processing the form compare the field and stored token.
(If you look at the implementation of MVC, there is very little more to it. A few helper methods is all you need.)

This is an old question, but the latest Visual Studio 2012 ASP.NET template for web forms includes anti CSRF code baked into the master page. If you don't have the templates, here's the code it generates:
Protected Sub Page_Init(sender As Object, e As System.EventArgs)
' The code below helps to protect against XSRF attacks
Dim requestCookie As HttpCookie = Request.Cookies(AntiXsrfTokenKey)
Dim requestCookieGuidValue As Guid
If ((Not requestCookie Is Nothing) AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue)) Then
' Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value
Page.ViewStateUserKey = _antiXsrfTokenValue
Else
' Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N")
Page.ViewStateUserKey = _antiXsrfTokenValue
Dim responseCookie As HttpCookie = New HttpCookie(AntiXsrfTokenKey) With {.HttpOnly = True, .Value = _antiXsrfTokenValue}
If (FormsAuthentication.RequireSSL And Request.IsSecureConnection) Then
responseCookie.Secure = True
End If
Response.Cookies.Set(responseCookie)
End If
AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
End Sub
Private Sub master_Page_PreLoad(sender As Object, e As System.EventArgs)
If (Not IsPostBack) Then
' Set Anti-XSRF token
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty)
Else
' Validate the Anti-XSRF token
If (Not DirectCast(ViewState(AntiXsrfTokenKey), String) = _antiXsrfTokenValue _
Or Not DirectCast(ViewState(AntiXsrfUserNameKey), String) = If(Context.User.Identity.Name, String.Empty)) Then
Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
End If
End If
End Sub

The C# version of Ian Ippolito answer here:
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
// The code below helps to protect against XSRF attacks
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
// Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
// Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
Page.ViewStateUserKey = _antiXsrfTokenValue;
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
HttpOnly = true,
Value = _antiXsrfTokenValue
};
if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
{
responseCookie.Secure = true;
}
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
}
else
{
// Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}

WebForms has a pretty similar analog in Page.ViewStateUserKey. By setting that to a per-user value (most choose HttpSessionState.SessionId), WebForms will validate the ViewState1 as part of the MAC check.
overrides OnInit(EventArgs e) {
base.OnInit(e);
ViewStateUserKey = Session.SessionId;
}
1 There are scenarios where ViewStateUserKey will not help. Mainly, they boil down to doing dangerous things with GET requests (or in Page_Load without checking IsPostback), or disabling ViewStateMAC.

You can use reflection to get at the MVC methods used to set the cookie and matching form input used for the MVC validation. That way you can have an MVC action with [AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken] attributes that you can post to from a WebForms generated page.
See this answer: Using an MVC HtmlHelper from a WebForm

Related

ValidateAntiForgeryToken in WebForms Application

I have done some reading about the use of ValidateAntiForgeryToken to prevent XSRF/CSRF attacks. However what I have seen seems to relate only to MVC.
These are the articles I've seen:
ValidateAntiForgeryToken purpose, explanation and example
CSRF and AntiForgeryToken
XSRF/CSRF Prevention in ASP.NET MVC and Web Pages
How can I implement this or something similar in a WebForms Application?
CSRF attacks are not exclusive to MVC application, webforms are vulnerable too.
Basically, CSRF attack exploits the trust that a site has in a user's browser, by requesting or posting information to the website, generally through hidden forms or JavaScript XMLHttpRequests within a the malicious website, as user using cookies stored in the browser.
To prevent this attacks you will need an antiforgery token, a unique token sent within your forms, that you need to validate before trusting the form's information.
You can find a detailed explanation here.
To protect your webforms apps against CSRF attacks (it's working in my projects), is to implement it in your master pages, like this:
Add new Class that will handle the CSRF Validations for you:
public class CsrfHandler
{
public static void Validate(Page page, HiddenField forgeryToken)
{
if (!page.IsPostBack)
{
Guid antiforgeryToken = Guid.NewGuid();
page.Session["AntiforgeryToken"] = antiforgeryToken;
forgeryToken.Value = antiforgeryToken.ToString();
}
else
{
Guid stored = (Guid)page.Session["AntiforgeryToken"];
Guid sent = new Guid(forgeryToken.Value);
if (sent != stored)
{
// you can throw an exception, in my case I'm just logging the user out
page.Session.Abandon();
page.Response.Redirect("~/Default.aspx");
}
}
}
}
Then implement this in your master pages:
MyMasterPage.Master.cs:
protected void Page_Load(object sender, EventArgs e)
{
CsrfHandler.Validate(this.Page, forgeryToken);
...
}
MyMaster.Master:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:HiddenField ID="forgeryToken" runat="server"/>
...
</form>
Hope you'll find this useful.
I found this article How To Fix Cross-Site Request Forgery (CSRF) using Microsoft .Net ViewStateUserKey and Double Submit Cookie with the following information code and instructions:
Starting with Visual Studio 2012, Microsoft added built-in CSRF protection to new web forms application projects. To utilize this code, add a new ASP .NET Web Forms Application to your solution and view the Site.Master code behind page. This solution will apply CSRF protection to all content pages that inherit from the Site.Master page.
The following requirements must be met for this solution to work:
•All web forms making data modifications must use the Site.Master
page.
•All requests making data modifications must use the ViewState.
•The web site must be free from all Cross-Site Scripting (XSS)
vulnerabilities. See how to fix Cross-Site Scripting (XSS) using
Microsoft .Net Web Protection Library for details.
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
//First, check for the existence of the Anti-XSS cookie
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
//If the CSRF cookie is found, parse the token from the cookie.
//Then, set the global page variable and view state user
//key. The global variable will be used to validate that it matches in the view state form field in the Page.PreLoad
//method.
if (requestCookie != null
&& Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
//Set the global token variable so the cookie value can be
//validated against the value in the view state form field in
//the Page.PreLoad method.
_antiXsrfTokenValue = requestCookie.Value;
//Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
//If the CSRF cookie is not found, then this is a new session.
else
{
//Generate a new Anti-XSRF token
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
//Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
//Create the non-persistent CSRF cookie
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
//Set the HttpOnly property to prevent the cookie from
//being accessed by client side script
HttpOnly = true,
//Add the Anti-XSRF token to the cookie value
Value = _antiXsrfTokenValue
};
//If we are using SSL, the cookie should be set to secure to
//prevent it from being sent over HTTP connections
if (FormsAuthentication.RequireSSL &&
Request.IsSecureConnection)
responseCookie.Secure = true;
//Add the CSRF cookie to the response
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
//During the initial page load, add the Anti-XSRF token and user
//name to the ViewState
if (!IsPostBack)
{
//Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
//If a user name is assigned, set the user name
ViewState[AntiXsrfUserNameKey] =
Context.User.Identity.Name ?? String.Empty;
}
//During all subsequent post backs to the page, the token value from
//the cookie should be validated against the token in the view state
//form field. Additionally user name should be compared to the
//authenticated users name
else
{
//Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] !=
(Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of
Anti-XSRF token failed.");
}
}
}
}
Using WebForms, the best thing to do is leverage the ViewStateUserKey.
Here is how to do it...
void Page_Init(object sender, EventArgs args)
{
ViewStateUserKey = (string)(Session["SessionID"] = Session.SessionID);
}
It seems kind of strange to save the SessionID in a session variable, but this is needed because it will auto-generate a new ID when empty.

Read cookie to login automatic

I store the cookies when someone is logging in, as below:
List<User> listUser;
//returns 1 user
foreach(User u in listUser)
{
HttpCookie cookieNickname = new HttpCookie("UserNickname");
cookieNickname.Value = u.Nickname.ToString();
cookieNickname.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookieNickname);
HttpCookie cookiePassword = new HttpCookie("UserPassword");
cookiePassword.Value = u.Password;
cookiePassword.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookiePassword);
}
When someone visits the site again, I want to read data from the database which is associated with usernickname-cookie and userpassword-cookie.
Then I want to show the firstname and lastname on a label.
This is what I tried:
List<User> cookieLoggedInUser;
if (Request.Cookies["UserNickname"] != null && Request.Cookies["UserPassword"] != null)
{
//returns 1 user
cookieLoggedInUser = Database.SignIn(Request.Cookies["UserNickname"].ToString(), Request.Cookies["UserPassword"].ToString());
if (cookieLoggedInUser.Count > 0)
{
foreach (User u in cookieLoggedInUser)
{
lblFirstName.Text = u.FirstName;
lblLastName.Text = u.LastName;
}
}
}
But both of the Request.Cookies return null.
Why is that happening?
I wouldn't recommend the approach you took other then for experimeting purposes as it has big security risk.
To make your curent solution work check that you are creating cookies in the same domain where you consume them.
If it is not the case, browser will not send cookies to the other domain.
You can make the sign-in cookie permanent using a technique like this:
protected void Login1_OnLoggedIn(object sender, EventArgs e)
{
CheckBox Remember = (CheckBox)((Login)sender).FindControl("Remember");
if (Remember.Checked)
{
FormsAuthenticationTicket t = new FormsAuthenticationTicket(2, Login1.UserName, DateTime.Now, DateTime.Now.AddYears(5), true, "");
string data = FormsAuthentication.Encrypt(t);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, data);
authCookie.HttpOnly = true;
authCookie.Domain = "";
authCookie.Expires = t.Expiration;
Response.Cookies.Remove("FORMAUTH");
Response.Cookies.Add(authCookie);
Response.Redirect(Request.QueryString["ReturnUrl"]);
}
}
This assumes the site is using asp.net membership services.
The line that says Response.Cookies.Remove("FORMAUTH"); should match the cookie name you have set up in your web.config under this section:
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/Login.aspx" name="FORMAUTH"/>
</authentication>
Wire this up to the OnLoggedIn event of your <asp:Login> control and when the user clicks Remember Me they stay logged in.
This is a lot safer than the alternative which you propose (storing unencrypted passwords in cookies).

Cookies and session in asp.net

I am creating a login and the storing the user details in a cookie using this code
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
//string useremail = Convert.ToString(txtUserName.Value);
Session.Add("useremail", txtUserName.Value);
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires=tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
}
I am also creating a session Session.Add("useremail", txtUserName.Value);
After succesfull authentication it is redirected to user.aspx
I want to read the useremail value in the user.aspx page but when I tried to access the value in the user page it is not showing useremail field.
protected void Page_Load(object sender, EventArgs e)
{
if
(Session["useremail"] == null) Response.Redirect("Home.aspx");
else
BindGridView(useremail);
}
And this is my webconfig:
<authentication mode="Forms"><forms name=".YAFNET_Authentication" loginUrl="Home.aspx" protection="All" timeout="43200" cookieless="UseCookies"/></authentication>
Correct me if i am doing any wrong. And also please tell me how to pass the useremail value to the user.aspx page so that I can pass that value to gridview function
Just change it to
protected void Page_Load(object sender, EventArgs e)
{
if (Session["useremail"] == null)
Response.Redirect("Home.aspx");
else
BindGridView((string)Session["useremail"]);
}
You can add an object to the session state like this:
Session["useremail"] = "john.smith#microsoft.com";
You can then retrieve it in the following manner:
var useremail = Session["useremail"] ?? null;
if (useremail == null)
{
//...
}
else
{
BindGridView(useremail);
}
If the item "useremail" is not present in the session state the useremail variable will be set to null otherwhise it will contain the e-mail address.
You are getting confused with relationship between authentication, session state and cookies.
In ASP.NET, Session State and Forms Authentication are not linked i.e. their scope are different. You can have some session state for un-authenticated user. Session and forms authentication uses different cookies for tracking purposes and the cookie management is more or less automatic and you don't really need to write code to manage it as you have done. Besides, what you store in the cookie has no bearing on what goes in the session state. Its also possible to have both session and forms authentication to get working w/o cookies. So code such as below should work for session state
Session["key"] = "put your data here";
// retrieve the data elsewhere
var data = Session["key"];

Securing a web service?

Question: I have a document management system, and I am building a Web-Service interfaces to the database.
Everything works so far, just that right now, it's totally unsecured, everybody can access it.
How can I incorporate password or private-public key authentication ?
I can only find 'best practises' and using 'windows user' or passport authentication.
But I need authentication from a user and password stored in the database, or better for an RSA private-key stored for each web-service user in the database...
Edit:
I have to use the .NET Framework 2.0 in an ASP.NET environment
The solution is to write an own http module with a mixture of code provided by MSDN and CodeProject. Including own fixes of MS bugs, and then add this custom soap header to the web service.
<SoapHeader("Authentication", Required:=True)>
This is the module:
Imports System.Web
Imports System.Web.Services.Protocols
' http://msdn.microsoft.com/en-us/library/9z52by6a.aspx
' http://msdn.microsoft.com/en-us/library/9z52by6a(VS.80).aspx
' http://www.codeproject.com/KB/cpp/authforwebservices.aspx
' http://aleemkhan.wordpress.com/2007/09/18/using-wse-30-for-web-service-authentication/
' http://www.codeproject.com/KB/WCF/CustomUserNamePassAuth2.aspx
' http://www.codeproject.com/KB/WCF/CustomUserNamePassAuth2.aspx
' http://www.codeproject.com/KB/webservices/WS-Security.aspx
'Public NotInheritable Class WebServiceAuthenticationModule
Public Class WebServiceAuthenticationModule
Implements System.Web.IHttpModule
Protected Delegate Sub WebServiceAuthenticationEventHandler(ByVal sender As [Object], ByVal e As WebServiceAuthenticationEvent)
Protected _eventHandler As WebServiceAuthenticationEventHandler = Nothing
Protected Custom Event Authenticate As WebServiceAuthenticationEventHandler
AddHandler(ByVal value As WebServiceAuthenticationEventHandler)
_eventHandler = value
End AddHandler
RemoveHandler(ByVal value As WebServiceAuthenticationEventHandler)
_eventHandler = value
End RemoveHandler
RaiseEvent(ByVal sender As Object,
ByVal e As WebServiceAuthenticationEvent)
End RaiseEvent
End Event
Protected app As HttpApplication
Public Sub Init(ByVal context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
app = context
context.Context.Response.Write("<h1>Test</h1>")
AddHandler app.AuthenticateRequest, AddressOf Me.OnEnter
End Sub
Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
' add clean-up code here if required
End Sub
Protected Sub OnAuthenticate(ByVal e As WebServiceAuthenticationEvent)
If _eventHandler Is Nothing Then
Return
End If
_eventHandler(Me, e)
If Not (e.User Is Nothing) Then
e.Context.User = e.Principal
End If
End Sub 'OnAuthenticate
Public ReadOnly Property ModuleName() As String
Get
Return "WebServiceAuthentication"
End Get
End Property
Sub OnEnter(ByVal [source] As [Object], ByVal eventArgs As EventArgs)
'Dim app As HttpApplication = CType([source], HttpApplication)
'app = CType([source], HttpApplication)
Dim context As HttpContext = app.Context
Dim HttpStream As System.IO.Stream = context.Request.InputStream
' Save the current position of stream.
Dim posStream As Long = HttpStream.Position
' If the request contains an HTTP_SOAPACTION
' header, look at this message.
'For Each str As String In context.Request.ServerVariables.AllKeys
'If context.Request.ServerVariables(Str) IsNot Nothing Then
'context.Response.Write("<h1>" + Str() + "= " + context.Request.ServerVariables(Str) + "</h1>")
'End If
'Next
If context.Request.ServerVariables("HTTP_SOAPACTION") Is Nothing Then
'context.Response.End()
Return
'Else
'MsgBox(New System.IO.StreamReader(context.Request.InputStream).ReadToEnd())
End If
' Load the body of the HTTP message
' into an XML document.
Dim dom As New System.Xml.XmlDocument()
Dim soapUser As String
Dim soapPassword As String
Try
dom.Load(HttpStream)
'dom.Save("C:\Users\Administrator\Desktop\SoapRequest.xml")
' Reset the stream position.
HttpStream.Position = posStream
' Bind to the Authentication header.
soapUser = dom.GetElementsByTagName("Username").Item(0).InnerText
soapPassword = dom.GetElementsByTagName("Password").Item(0).InnerText
Catch e As Exception
' Reset the position of stream.
HttpStream.Position = posStream
' Throw a SOAP exception.
Dim name As New System.Xml.XmlQualifiedName("Load")
Dim ssoapException As New SoapException("Unable to read SOAP request", name, e)
context.Response.StatusCode = System.Net.HttpStatusCode.Unauthorized
context.Response.StatusDescription = "Access denied."
' context.Response.Write(ssoapException.ToString())
'Dim x As New System.Xml.Serialization.XmlSerializer(GetType(SoapException))
'context.Response.ContentType = "text/xml"
'x.Serialize(context.Response.OutputStream, ssoapException)
'Throw ssoapException
context.Response.End()
End Try
' Raise the custom global.asax event.
OnAuthenticate(New WebServiceAuthenticationEvent(context, soapUser, soapPassword))
Return
End Sub 'OnEnter
End Class ' WebServiceAuthenticationModule
If you are still using an ASP.NET SOAP web service then the easiest way that fits your requirements IMO is to use the ASP.NET Forms authentication with a Membership DB. If you are starting out fresh I'd recommend going with WCF - if you can't/or won't do that this post applies to the "classic" ASP.NET SOAP web services.
To add Forms authentication to a web service:
Configure it just like you would for any other web site but set it to allow access for everyone:
<authorization>
<allow users="*"/>
</authorization>
Implement Login/Logout methods and issue the authentication ticket in the Login method. Further requests to the web service then can use the issued authentication ticket.
All other web methods you want to protect you can then decorate with
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
These methods will now throw a Security exception if a client is not authenticated.
Example for a protected method:
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
[WebMethod(Description = "Your protected method")]
public string Foo()
{
return "bar";
}
Example for Login method:
[WebMethod(Description = "Login to start a session")]
public bool Login(string userName, string password)
{
if (!Membership.Provider.ValidateUser(userName, password))
return false;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(500),
false,
FormsAuthentication.FormsCookiePath);// Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent)
cookie.Expires = ticket.Expiration;
// Add the cookie to the list for outgoing response
if(HttpContext.Current !=null)
HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.SetAuthCookie(userName, true);
return true;
}
If you are working with WCF, there's an easy way to implement security using X509 certificates. Implementing a binding with security mode 'Message' and clientCredentialType 'Username' it's possible to guarantee this security in a automated way.
The validation can be made through a class wich overrides a method Validate.
http://msdn.microsoft.com/en-us/library/aa702565.aspx
If your WS is going to be consumed through SOAP protocol, the you can implement the Security through the SOAP Header:
using System.Web.Services;
using System.Web.Services.Protocols;
namespace Domain.WS
{
[Serializable]
public class SoapWSHeader : System.Web.Services.Protocols.SoapHeader, ISoapWSHeader
{
public string UserId { get; set; }
public string ServiceKey { get; set; }
public ApplicationCode ApplicationCode { get; set; }
}
[WebService(Namespace = "http://domain.some.unique/")]
public class MyServices : System.Web.Services.WebService
{
public SoapWSHeader WSHeader;
private ServicesLogicContext _logicServices;
public MyServices() { _logicServices = new ServicesLogicContext(new LogicInfo() {...}); }
[WebMethod, SoapHeader("WSHeader", Direction = SoapHeaderDirection.InOut)]
public Result WSMethod1(Int32 idSuperior)
{
_logicServices.ThrowIfNotAuthenticate(WSHeader);
return _logicServices.WSMethod1(idSuperior) as Result;
}
}
}
namespace Domain.Logic
{
[Serializable]
public class ServicesLogicContext : ServicesLogicContextBase
{
protected ISoapWSHeader SoapWSHeader { get; set; }
public ServicesLogicContext(LogicInfo info) : base(info) {}
public IResult WSMethod1(Int32 idSuperior)
{
IResult result = null;
//-- method implementation here...
return result;
}
public void ThrowIfNotAuthenticate(ISoapWSHeader soapWSHeader) {
this.SoapWSHeader = soapWSHeader;
if (SoapWSHeader != null)
{
if (!ValidateCredentials(soapWSHeader))
{
throw new System.Security.SecurityException(Resources.ValidationErrorWrongCredentials);
}
}
else { throw new System.Security.SecurityException(Resources.ValidationErrorWrongWSHeader); }
}
private bool ValidateCredentials(ISoapWSHeader soapWSHeader) {
return (SoapWSHeader.UserId.Equals("USER_ID") && SoapWSHeader.ServiceKey.Equals("PSW_1"));
}
}
}
Note: this code is not complete, this only depicts the main aspects on how to use the SOAP Header.
Before you roll your own authentication, you might want to have a look at Web Services Enhancements (WSE) 2.0 SP3 for Microsoft .NET. It's an implementation of the WS-Security specification for .net.
google wse 2.0 or WS-Security for more links.

Setting ViewStateUserKey gives me a "Validation of viewstate MAC failed" error

I have the following in my BasePage class which all my ASPX pages derive from:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
ViewStateUserKey = Session.SessionID;
}
I also have a machineKey set in Web.config. I don't think this error is because of a web farm because this happens on my dev machine too.
My host has now upgraded to .NET 3.5 SP1. After this update, everytime I compile with the ViewStateUserKey setting above, I constantly get the "Validation of viewstate MAC failed" error on every postback.
What am I doing wrong here? Is this setting even necessary anymore with the latest framework update?
OK - Im a year late to the conversation - but how is this the correct answer? This applies only in the case of authenticated users and using the ViewStateUserKey as the username is a lot easier to guess than a session id GUID.
BTW if you want to 'fix' the code up top, use the Session ID, however you must set a session variable in order for the session id to stop from changing every time. Ex.
Session["Anything"] = DateTime.Now
ViewStateUserKey = Session.SessionID;
This of course is assuming you are going to use sessions, otherwise you need some other key to use such as the username or any other guid kept in a cookie.
I've searched around quite a bit to find the definitive cause of the issue.
This post from Microsoft really helped explain all the different causes.
http://support.microsoft.com/kb/2915218
Cause 4 is what we have landed on which is an invalid ViewStateUserKeyValue
Setting ViewStateUserKey to Session.SessionID or User.Identity.Name did not work for us.
We intermittently got the validation error due to the following.
When the application pool is reset by IIS, the session is renewed in effect causing the error.
We drop the Session on login to avoid session fixation, also resulting in the error on login.
What finally worked for us was a cookie based solution, which is now provided in VS2012.
public partial class SiteMaster : MasterPage
{
private const string AntiXsrfTokenKey = "__AntiXsrfToken";
private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
private string _antiXsrfTokenValue;
protected void Page_Init(object sender, EventArgs e)
{
//First, check for the existence of the Anti-XSS cookie
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
//If the CSRF cookie is found, parse the token from the cookie.
//Then, set the global page variable and view state user
//key. The global variable will be used to validate that it matches in the view state form field in the Page.PreLoad
//method.
if (requestCookie != null
&& Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
{
//Set the global token variable so the cookie value can be
//validated against the value in the view state form field in
//the Page.PreLoad method.
_antiXsrfTokenValue = requestCookie.Value;
//Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
//If the CSRF cookie is not found, then this is a new session.
else
{
//Generate a new Anti-XSRF token
_antiXsrfTokenValue = Guid.NewGuid().ToString("N");
//Set the view state user key, which will be validated by the
//framework during each request
Page.ViewStateUserKey = _antiXsrfTokenValue;
//Create the non-persistent CSRF cookie
var responseCookie = new HttpCookie(AntiXsrfTokenKey)
{
//Set the HttpOnly property to prevent the cookie from
//being accessed by client side script
HttpOnly = true,
//Add the Anti-XSRF token to the cookie value
Value = _antiXsrfTokenValue
};
//If we are using SSL, the cookie should be set to secure to
//prevent it from being sent over HTTP connections
if (FormsAuthentication.RequireSSL &&
Request.IsSecureConnection)
responseCookie.Secure = true;
//Add the CSRF cookie to the response
Response.Cookies.Set(responseCookie);
}
Page.PreLoad += master_Page_PreLoad;
}
protected void master_Page_PreLoad(object sender, EventArgs e)
{
//During the initial page load, add the Anti-XSRF token and user
//name to the ViewState
if (!IsPostBack)
{
//Set Anti-XSRF token
ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
//If a user name is assigned, set the user name
ViewState[AntiXsrfUserNameKey] =
Context.User.Identity.Name ?? String.Empty;
}
//During all subsequent post backs to the page, the token value from
//the cookie should be validated against the token in the view state
//form field. Additionally user name should be compared to the
//authenticated users name
else
{
//Validate the Anti-XSRF token
if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
|| (string)ViewState[AntiXsrfUserNameKey] !=
(Context.User.Identity.Name ?? String.Empty))
{
throw new InvalidOperationException("Validation of
Anti-XSRF token failed.");
}
}
}
}
Source
I fixed it for now by changing the code to:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (User.Identity.IsAuthenticated)
ViewStateUserKey = User.Identity.Name;
}
Can you turn off ViewState MAC encoding with the EnableViewStateMac #Page attribute?
VERY Strange, I too had similar issue for 3 days and now i resolved it.
1. I had enabled forms authentication and had ssl false
<forms defaultUrl="~/" loginUrl="~/Account/Login.aspx" requireSSL="false" timeout="2880" />
but in my httpcookies tag I had requireSSL=true. Since in the Site.Master.cs it uses cookies to set the ViewStateUserKey, it was having issues
hence I was getting the error.
I modified this to false and restarted web app, now its all good.

Categories