TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Akash Dani
NA
87
25.4k
How to implement and Validate CSRF method in asp.net
Sep 6 2019 1:20 AM
I am using asp.net application and I dont know how to implement and validate CSRF tokens in asp.net.I want to validate these tokens in each request.
Can anyone help me?
And I have added this following code in Masterpage
private
const
string
AntiXsrfTokenKey =
"__AntiXsrfToken"
;
private
const
string
AntiXsrfUserNameKey =
"__AntiXsrfUserName"
;
private
string
_antiXsrfTokenValue;
protected
void
Page_Init(
object
sender, EventArgs e) {
var requestCookie = Request.Cookies[AntiXsrfTokenKey];
Guid requestCookieGuidValue;
if
(requestCookie !=
null
&& Guid.TryParse(requestCookie.Value,
out
requestCookieGuidValue)) {
_antiXsrfTokenValue = requestCookie.Value;
Page.ViewStateUserKey = _antiXsrfTokenValue;
}
else
{
_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) {
try
{
if
(!IsPostBack) {
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."
);
}
}
}
catch
(Exception ex) {
activityLog.Write(
"MasterPage->PageLoad->Exception->"
+ ex.Message.ToString());
Session.Clear();
Session.RemoveAll();
Session.Abandon();
Response.Cookies[
"ASP.NET_SessionId"
].Expires = DateTime.Now.AddYears(-30);
Response.Cookies.Add(
new
HttpCookie(
"ASP.NET_SessionId"
,
""
));
ScriptManager.RegisterStartupScript(
this
, GetType(),
"DeleteCookie"
,
"DeleteCookie();"
,
true
);
Response.Redirect(
"Default.aspx"
,
false
);
}
}
Reply
Answers (
1
)
I need to implement grammatical check in .net windows form.
Present address and permaent address if it will be same