How to prevent people from keep looping HTTP POST to a function? - c#

I am trying to develop a website, the website got a pop-up modal which allows the user to subscribe to our latest promotion. In that input, we got a textbox to allow users to key in their email.
However, when we look at the HTML code, the HTTP POST URL is visible:
If someone is trying to use this URL, and spam HTTP POST requests (see below), unlimited entries can be created in the subscriber database table.
for (int a = 0; a < 999999; a++)
{
var values = new Dictionary<string, string>
{
{ "email", a+"#gmail.com" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
How can I prevent this from happening? We cannot put a capcha, since this is subscriber to our promotion.
Edit: Please note that a ANTI-forgery token will not work, because the hacker can download entire HTML string using GET, and get the value from the anti forgery token textbox and POST the value to the POST URL again, so it will not work and the same anti-forgery token can use multiple times, it is not secure.

You can choose one of the below option to implement what you are looking for.
1- Implement CAPTCHA/re-CAPTCHA, it will make sure that using any tool request can't be made. I understand that you don't want to use CAPTCHA, I still feel you should go with it, as it is the best approach to handle this type of scenarios.
2- IP Based restriction, lock submitting the request from one IP for some time.
3- Other option can be OTP (one time password), you can send the OTP to the email, and only after successful verification you can register the email.

Use AntiForgeryToken. Read more about Antiforgery Tokens here
In your form Razor View, Add an #Html.AntiForgeryToken() as a form field.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#*Rest of the form*#
}
In your Action Method use ValidateAntiForgeryTokenAttribute
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit( MyViewModel form)
{
if (ModelState.IsValid)
{
// Rest of ur code
}
}

Related

Writing Cookie on successful submit in Blazor Application

I have a login page that allows the user to login. In the HandlieValidSubmit() event I check if username and password matches with the value stored in database.
If everything is fine I want to store some data into the usercookie before redirecting to another site. This is the html/blazor-Code:
<EditForm>
<!-- standard form-controls here -->
</EditForm>
#code {
private Models.LoginUser _loginUser = new Models.LoginUser();
private EditContext _editContext;
private void HandleValidSubmit()
{
if (UserApi.Login(_loginUser.Mail, _loginUser.Password, out string error, out Guid? guid))
{
NaviationManager.NavigateTo($"/manage/{guid}");
}
}
}
the Cookie is set from within the Login-Function and looks like this:
public DateTime SetCookie<T>(T data, TimeSpan expiration, bool httpOnly = true, bool secure = true)
{
DateTime expireDate = DateTime.Now.Add(expiration);
if (data == null) return DateTime.Now;
Type dataType = typeof(T);
var response = _httpContextAccessor.HttpContext.Response;
CookieOptions cookieOptions = new CookieOptions
{
HttpOnly = httpOnly,
Secure = secure,
Expires = expireDate
};
foreach (var property in dataType.GetProperties())
{
var storeInCookieAttribute = property.GetCustomAttribute<StoreInCookieAttribute>();
if (storeInCookieAttribute == null) continue;
response.Cookies.Append(BuildCookieKey(dataType.Name, property.Name), property.GetValue(data) as string, cookieOptions);
}
return expireDate;
}
IMHO this is the standard "how-to-write-cookies-in-netcore" - way.
When I try to write the cookie I receive the error:
"The response headers cannot be modified because the response has already started."
I understand what this error wants to tell me. Alas I do not really know how to prevent this. I expected that at this point the response should not have started at all.
Is there another event than HandleValidSubmit() I need to use instead? Or can I just clear the Response before writing the cookie without bad side effects?
Blazor Server App is websocket-based application, not HTTP-based one, so the HttpContext service is not available.
When you create a Blazor Server App with support for IdentityUI, you get in the default template a component ( AuthorizeView ) that enables login and logout. When you click on the "Login" button, you are being redirected to a Login page where you can enter your credentials. The Login page is actually a Razor Page, not part of the Blazor App, meaning that you are no longer in the realm of Blazor, and here in this new realm (The Razor Page), the HttpContext is available, you don't even have to use the HttpContextAccessor, as the HttpContext is provided as a property in the PageModel object. After the user has been logged in, cookies created, etc., he is redirected to Blazor.
This is how you can do it. Just emulate this procedure... Create a Razor Page, where you can do all that stuff. You may also pass a return url, so that you'll be redirected to a specific Component page instead of the the Index Component Page.
Note: HandleValidSubmit() is a method that is called if your forms component elements have passed validation. It has got nothing to do with the issue in question.
Note: To use the NavigationManger.NavigateTo method to navigate to external location (outside of the Blazor App realm), add a second boolean parameter with the value true.
Note: This may help you how to cope . There are also many answers related to the current subject and authentication with OpenID Connect, Okta, IdentityUI, etc. Just look for them if you are in need.
Note: Are you aware that you can store data in the local storage and session storage ?
Hope this helps...

Embedding: ViewLinkRequest.ReturnUrl doesn't work as expected

I'm using docusign-csharp-client and following code snippet to receive the view url for completed envelope, and suppose to be redirected to returnUrl once close action would be performed by the user, who consumes the generated link.
var link = _envelopesApi.CreateViewLink(accountId, envelopeId, new ViewLinkRequest { ReturnUrl = returnUrl, Email = consumerEmail });
As a result user receives an envelope view, but after closing it she gets redirected on my docusing account home page instead of expected returnUrl.
Is there any straightforward way to achieve what I need in Embedded Workflows?
Display the completed document
Redirect consuming user to my return url
It's demo account.
I'd use the embedded recipient view. It can be used even after the recipient has viewed.
Or an easier answer is to fetch the documents from DocuSigh to your server and then show them to your users as appropriate.
The ViewLink method doesn't do what you want and is deprecated.

How to resolve: The provided anti-forgery token was meant for a different claims-based user than the current user

I am getting this error:
The provided anti-forgery token was meant for a different claims-based user than the current user.
and I am not sure how to correct this..
I have a MVC5 site and in this site I have a login page.
This is the scenario that it occurs on.
User AAA logs in. (No issues)
I attempt to access a view where the user does not have access.
I have the class decorated with an Authorize(Roles="aa")
The view then logs the user off and puts them back to the login page.
User AAA logs in. (This time I get the error mentioned above)
To note:
I am using customErrors and this is where I see the error message.
When I log the user out I am running this method:
[HttpGet]
public void SignOut()
{
IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut(MyAuthentication.ApplicationCookie);
}
Could I possibly be missing something on the SignOut?
UPDATE:
This only occurs because of step #2 listed above.
If I log in, then log out (calling same code) then log back in, then I do not have this issue.
I think you've neglected to post some relevant code. The Signout action you have returns void. If you were to access this action directly in the browser, then the user would get a blank page after being signed out with no way to progress forward. As a result, I can only assume you are either calling it via AJAX or calling as a method from another action.
The way anti-forgery works in MVC is that a cookie is set on the user's machine containing a unique generated token. If the user is logged in, their username is used to compose that token. In order for a new cookie, without a username to be set, the user must be logged out and a new request must occur to set the new cookie. If you merely log the user out without doing a redirect or something, the new user-less cookie will not have been set yet. Then, when the user posts, the old user-based cookie is sent back while MVC is looking for the new user-less cookie, and boom: there's your exception.
Like I said, you haven't posted enough code to determine exactly why or where this is occurring, but simply, make sure there is a new request made after logging the user out, so the new cookie can be set.
I was able to reproduce by clicking on the login button more than once before the next View loads. I disabled the Login button after the first click to prevent the error.
<button type="submit" onclick="this.disabled=true;this.form.submit();"/>
Disable the identity check the anti-forgery validation performs. Add the following to your Application_Start method:
AntiForgeryConfig.SuppressIdentityHeuristicChecks = true.
try:
public ActionResult Login(string modelState = null)
{
if (modelState != null)
ModelState.AddModelError("", modelState);
return View();
}
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model)
{
AuthenticationManager.SignOut();
return RedirectToAction("Login", "Controller", new { modelState = "MSG_USER_NOT_CONFIRMED" });
}
I haved similar problem. I found this text "#Html.AntiForgeryToken() " in my project in 2 place. And one plase will was in "view file" Views - test.cshtml.
#using (Html.BeginForm())
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#if (#Model.interviewed)
...
I deleted this code line ("#Html.AntiForgeryToken() ") and working fine.
PS: But I am not delete this code in file _LoginPartial.cshtml.
Good luck!

Is sending Session from javascript safe?

Well, this is a bit weird i think to ask this question, because i am not sure if that's the place to ask that.
OK, into the question..
I have this code
<script>
var session = "<%= Session["User"]%>";
</script>
So, i was thinking, is that safe? let me tell you what i mean..
I have a web api which you can get the name, last name, age and everything about the user with his Session, can i send this web api this session and use it?
Is that a safe thing to do ? in matter of securiy? if not, is there any better way?
EDIT 1:
What am i trying to aaccomplish? simple, i will store the UserId in the session, the UserId will Guid, when the user is loogin in the javascript can send post to an API server to get info, the API will send the UserId from the session.
Is That ok?
Workflow that you describe looks fine. For me it seems safe to use some ID to get more information about some user, especially if this is supposed to be an API, at least, Facebook API uses such principle not being afraid of some hackers :)
My main concern here is the coding style when you try to mix code and view which is not good. If you really need to share some information between client and server sides then I would go with one of these options.
Option # 1 - Cookies
What is the difference between a Session and a Cookie?
You can keep some simple information in a cookie and get it this way :
Client : $.cookie('ID')
Server : Response.Cookies["ID"]
In this case there is no need to put in a mess your client side JS with C# code and cookies will be saved on users PC which means that nobody will see them except him.
Option # 2 - Templates
Server : put all needed information into hidden form or ViewState
Client : take information from hidden form using HTML selectors
Straight answer :
In general, if you worry only about safety then it is fine to use this code, it should not break security of your site.
Although, personally I do not like this approach because :
you will mix code and view, MVC was created to split them
it is not clear where exactly in your view you will put this code and thus it is not clear how you are going to check that this variable was initialized
it may happen that you will put there some value that will break JS syntax and will cause JS error
In my personal opinion, I would replace it with one of the mentioned options.
Option 1 - MVC + JQuery + Cookie Example
public ActionResult Index()
{
string demo = Request.QueryString["MyNameSpace.ID"]; // get value from client
Response.Cookies["MyNameSpace.ID"].Value = "server"; // change value in response
return View();
}
Then in your JS file :
$(document).ready(function() { // make sure server rendered page
var ID = $.cookie('MyNameSpace.ID'); // get cookie value from server
$.cookie('MyNameSpace.ID', 'client'); // update, on the next request server will get it
});
Option 2 - MVC + JQuery + Templates Example
public class OptionsModel // View Model
{
public string ID { get; set; }
public string User { get; set; }
}
public ActionResult Index() // Controller
{
OptionsModel options = new OptionsModel();
options.ID = "server";
return View(options);
}
Your view :
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<OptionsModel>" %>
<%=Html.HiddenFor(m => Model.ID, new { #class = "MyNameSpace:ID" })%>
<%=Html.HiddenFor(m => Model.User, new { #class = "MyNameSpace:User" })%>
Then in your JS file :
$(document).ready(function() { // make sure server rendered page
var options = $('[class^=MyNameSpace]') // get values from hidden fields
options[0] = 'client'; // update data
$.ajax({ data : options }); // create handler to send data back to server
});
Examples for Web Forms do not differ significantly.
The code you have posted will be rendered on the page as so when it hits the client (assuming you are using ASP.NET
<script>
var session = "John Smith";
</script>
This is due to the use of the server side scripting tags <%= %> (https://technet.microsoft.com/en-us/library/cc961121.aspx)
As a note its probably not the best thing in the world to fully expose the session to javascript if that is your intention. At the end of the day it depends what you are storing in there and using it for (but ASP.NET will also use it for certain things) but exposing it just opens another area for someone to attack.
http://www.owasp.org is a great place to learn more about securing your website.

How to pass query string parameter in asp.net?

I am using Access Control service (ACS). I fetched all identity providers (ip) which i set for my application using the following code :
public ActionResult IdentityProviders(string serviceNamespace, string appId)
{
string idpsJsonEndpoint = string.Format(Global.IdentityProviderJsonEndpoint, serviceNamespace, appId);
var client = new WebClient();
var data = client.DownloadData(idpsJsonEndpoint);
return Content(Encoding.UTF8.GetString(data), "application/json");
}
When user click over the signin link the above code called using ajax and get the ips and display them in jquery-ui dialog. And when user click any one of the ips for login the browser redirect to the selected ip login page. After successful login the control return to my control which i set as a returnUrl. Upto this every thing is works fine.
Now what i am trying to do is to pass some values to identity provider (ip) login page and want to get back those values at my returnUrl controller. For this i searched and came to know that there is a query string parameter known as wctx which we can set and get the value at return url. But i dont know how to do this. Can anybody please guid me how can i achieve this?
It is relatively (pretty) easy.
Your URL for listing IdPs looks something like this:
https://[your_namespace].accesscontrol.windows.net:443/v2/metadata/IdentityProviders.js?protocol=wsfederation&realm=[your_realm]&reply_to=[configured_return_url_for_your_rp]&context=&request_id=&version=1.0&callback=
This is the most complete request for list of Identity Providers. Your may miss some variables (such as context, or reply_to), but what I show is the complete request.
So now you have two options:
inclide your own reply_to parameter. It must be withing the configured realm. So if your realm is https://www.mygreatapp.com/, your default return URL would probably be something like https://www.mygreatapp.com/returnUrl/ (if your controller to handle ACS response is returnUrlController. Now, you can safely change the reply_to to be https://www.mygreatapp.com/returnUrl/?foo=bar, just make sure you URL Encode the query string.
Use the context parameter. It is safer to use and I would suggest using it. Now your URL for fetching list of IdPs will be something like:
https://[your_namespace].accesscontrol.windows.net:443/v2/metadata/IdentityProviders.js?protocol=wsfederation&realm=[your_realm]&reply_to=[configured_return_url_for_your_rp]&context=[your_custom_string_value_which_you_may_even_encrypt]&request_id=&version=1.0&callback=
Note the now there is context value present in the request for IdP list ([your_custom_string_value_which_you_may_even_encrypt]). In your returnUrl handler controller, you can check for it with code similar (or equal) to the following:
if (ControllerContext.HttpContext.Request.Form["wresult"] != null)
{
// This is a response from the ACS - you can further inspect the message if you will
SignInResponseMessage message =
WSFederationMessage.CreateFromNameValueCollection(
WSFederationMessage.GetBaseUrl(ControllerContext.HttpContext.Request.Url),
ControllerContext.HttpContext.Request.Form)
as SignInResponseMessage;
if (!string.IsNullOrWhiteSpace(message.Context))
{
// do whatever you want with the context value
}
}
You may want to perform any/more additional checks while handling the SignInResponse from ACS.

Categories