ASP.NET MVC: What's the best way to validate the expiry/legitimate of querysting - asp.net

We have a payment successful page where we read the query string ?paid=yes.
If paid=yes then we show the payment sucessfull message etc. Otherwise payment failed.
What's the best way to:
Validate ?paid=yes query string is valid? In other words, how can we stop people from manually manipulating query string ?
Set query string expiry time or set attempt (max 1)?
Thanks.

As usual: never trust user input. The only difference between a request with ?paid=yes or not in the querystring would be the message you show. You have to find a different way to validate the payment by communicating with the payment provider directly to check the result.

In my opinion you cant validate a payment in a query, I would instead give the client a ticket, so now the query would be ?ticket=UUID, where uuid can be generated with GUID class Giud.NewGuid().
now in the database of your server you should create the ticket too and a boolean field indicating if the payment is done.

Related

How to eliminate false success messages when implementing post-redirect-get pattern?

When implementing the post-redirect-get pattern in a web application, it is common for the final step in your server code to look something like this (pseudocode):
if (postSuccessful)
{
redirect("/some-page?success=true")
}
That is, the redirect URL has some kind of success parameter in the query string so that you know when to display a nice looking "Your form has been submitted!" message on your page. The problem with this is that the success=true persists in the query string when it's only needed to initialize the page. If the user refreshes the page or bookmarks it, they will receive a false success message even though no additional POST has taken place.
Is there an elegant solution to this that doesn't involve using JavaScript to eliminate success=true from both the query string and the browser history? This solution works, but definitely adds complexity to a page's load process.
You can use server side technology to implement this feature, without any JavaScript. The stes are listed below:
When post is successful, redirect to /some-page with current timestamp information:
if (postSuccessful)
{
redirect("/some-page?success=true&timestamp=1559859090747")
}
When server receives GET /some-page?success=true&timestamp=1559859090747 request, compare the timestamp parameter with the current timestamp, check whether it is within the last 3 seconds (or you can change this number according to the network environment).
If the timestamp parameter is within last 3 seconds, then it means this GET /some-page?success=true request is a result of server redirect. If not, then it's more like a result of "user refreshes the page or bookmarks it".
In server code that handling GET /some-page, render different HTML according to the result of step 3. Display the success message only when current access is a result of server redirect.

How to set expiration time for a link sent via Email?

I send a link as email to the users asking them to reset the password. Clicking on the link redirects to a page in my project. How can I set the expiration time for this link to 24 hours, and how do I know if this link is not re-used again? Whats the best way to do this?
Thanks
I dont know how your process looks like but the recommend way is to use a guid to identify the
passwort reset process.
This is how a process should look like.
Create a database table with the userId, createDate, closeDate, and a guid
Create a new entry in the table
Send the mail with a link to your page that has the uuid from the entry
If the user enters the page (clicks the link) you check if the process is still open (closeDate is null)
Check if the createDate is within the last 24 hours
User can change password
You set the closeDate
store email sent date&time in the database(where your maintaning userdetails) .
when your are open link for reset password capture present date. compare both date&time values . they you can procced. may this helps you.
I have an idea
Create a Time.now() and encrypt this using encryption and attach with your link
Send using Email and other option
go to the link page
write code on page load Request the sent encrypted Date Time and decipher it
match time if time is over then send to an error page else continue
Like -:- http://Yourhost/foldername.aspx?val=encryptedTimeDate

How to expose a validation API in a RESTful way?

I'm generally a fan of RESTful API design, but I'm unsure of how to apply REST principles for a validation API.
Suppose we have an API for querying and updating a user's profile info (name, email, username, password). We've deemed that a useful piece of functionality to expose would be validation, e.g. query whether a given username is valid and available.
What are the resource(s) in this case? What HTTP status codes and/or headers should be used?
As a start, I have GET /profile/validate which takes query string params and returns 204 or 400 if valid or invalid. But validate is clearly a verb and not a noun.
The type of thing you've described is certainly more RPC-style in its' semantics, but that doesn't mean you can't reach your goals in a RESTful manner.
There's no VALIDATE HTTP verb, so how much value can you get from structuring an entire API around that? Your story centers around providing users with the ability to determine whether a given user name is available - that sounds to me like a simple resource retrieval check - GET: /profile/username/... - if the result is a 404, the name is available.
What this highlights is that that client-side validation is just that - client side. It's a UI concern to ensure that data is validated on the client before being sent to the server. A RESTful service doesn't give a whit whether or not a client has performed validation; it will simply accept or reject a request based on its' own validation logic.
REST isn't an all-encompassing paradigm, it only describes a way of structuring client-server communications.
We have also encountered the same problem. Our reasoning for having the client defer to the server for validation was to prevent having mismatched rules. The server is required to validate everything prior to acting on the resources. It didn't make sense to code these rules twice and have this potential for them to get out of sync. Therefore, we have come up with a strategy that seems to keep with the idea of REST and at the same time allows us to ask the server to perform the validation.
Our first step was to implement a metadata object that can be requested from a metadata service (GET /metadata/user). This metadata object is then used to tell the client how to do basic client side validations (requiredness, type, length, etc). We generate most of these from our database.
The second part consist of adding a new resource called an analysis. So for instance, if we have a service:
GET /users/100
We will create a new resource called:
POST /users/100/analysis
The analysis resource contains not only any validation errors that occurred, but also statistical information that might be relevant if needed. One of the issues we have debated was which verb to use for the analysis resource. We have concluded that it should be a POST as the analysis is being created at the time of the request. However, there have been strong arguments for GET as well.
I hope this is helpful to others trying to solve this same issue. Any feedback on this design is appreciated.
You are confusing REST with resource orientation, there's nothing in REST that says you cannot use verbs in URLs. When it comes to URL design I usually choose whatever is most self-descriptive, wheather is noun or verb.
About your service, what I would do is use the same resource you use to update, but with a test querystring parameter, so when test=1 the operation is not done, but you can use it to return validation errors.
PATCH /profile?test=1
Content-Type: application/x-www-form-urlencoded
dob=foo
... and the response:
HTTP/1.1 400 Bad Request
Content-Type: text/html
<ul class="errors">
<li data-name="dob">foo is not a valid date.</li>
</ul>
A very common scenario is having a user or profile signup form with a username and email that should be unique. An error message would be displayed usually on blur of the textbox to let the user know that the username already exists or the email they entered is already associated with another account. There's a lot of options mentioned in other answers, but I don't like the idea of needing to look for 404s meaning the username doesn't exist, therefore it's valid, waiting for submit to validate the entire object, and returning metadata for validation doesn't help with checking for uniqueness.
Imo, there should be a GET route that returns true or false per field that needs validated.
/users/validation/username/{username}
and
/users/validation/email/{email}
You can add any other routes with this pattern for any other fields that need server side validation. Of course, you would still want to validate the whole object in your POST.
This pattern also allows for validation when updating a user. If the user focused on the email textbox, then clicked out for the blur validation to fire, slightly different validation would be necessary as it's ok if the email already exists as long as it's associated with the current user. You can utilize these GET routes that also return true or false.
/users/{userId:guid}/validation/username/{username}
and
/users/{userId:guid}/validation/email/{email}
Again, the entire object would need validated in your PUT.
It is great to have the validation in the REST API. You need a validation anyway and wy not to use it on the client side. In my case I just have a convention in the API that a special error_id is representing validation errors and in error_details there is an array of error messages for each field that has errors in this PUT or POST call. For example:
{
"error": true,
"error_id": 20301,
"error_message": "Validation failed!",
"error_details": {
"number": [
"Number must not be empty"
],
"ean": [
"Ean must not be empty",
"Ean is not a valid EAN"
]
}
}
If you use the same REST API for web and mobile application you will like the ability to change validation in both only by updating the API. Especialy mobile updates would take more than 24h to get published on the stores.
And this is how it looks like in the Mobile application:
The response of the PUT or POST is used to display the error messages for each field. This is the same call from a web application using React:
This way all REST API response codes like 200 , 404 have their meaning like they should. A PUT call responses with 200 even if the validation fails. If the call passes validation the response would look like this:
{
"error": false,
"item": {
"id": 1,
"created_at": "2016-08-03 13:58:11",
"updated_at": "2016-11-30 08:55:58",
"deleted_at": null,
"name": "Artikel 1",
"number": "1273673813",
"ean": "12345678912222"
}
}
There are possible modifications you could make. Maby use it without an error_id. If there are error_details just loop them and if you find a key that has the same name as a field put his value as error text to the same field.

Can I read Captcha data from JavaScript in a secure way?

We use Captcha control in a registration form that we make full client validation for all fields in JavaScript ( JQuery ) beside server validation ..
I tried a lot of ways but all will write the Captcha value in JavaScript that can be accessed by anyone :(
I search if is there any way that allow me validate Captcha value in client side using JQuery in secure way or it can't be done ?
It cannot be done.
Javascript is client-side, as you know, and any code client-side has to be treated as potentially compromised as you don't have control over it.
At best, you could resort to sending up a salted hash of the value along with the salt, but even that in itself could be used to test guess values before actually submitting it.
Everything else relies on calls to the server.
As per comment request, here's the general idea:
Firstly, on the server, calculate a random string to be used as the salt. This should be roughly unique every request. The purpose of this string is to prevent rainbow table attacks.
Now, saving this string separately, but also create another string that is the concatenation of random string and the Captcha answer. Of this new combined string you generate the hash (for example, SHA-1) of it.
using System.Web.Security;
...
string hashVal = FormsAuthentication.HashPasswordForStoringInConfigFile(combined, "SHA1");
Both the random string and the hash value need to be placed in the page for the javascript to be able to read.
On the client side, when a user answers the Captcha, take the random string and concatenate it with the answer (getting the idea here?). Taking this string, you can use something like the SHA-1 JQuery plugin to hash it and compare it with the pre-computed hash you sent up.
hashVal = $.sha1(combinedString)
If it matches, it is (almost) certainly the correct answer. If it doesn't, then it is 100% the wrong answer.
you could use ajax to post the current value to the server, which would respond true or false. that would keep you from doing a real post and also from giving away the catpcha's value in html.
My solution )) Every time when page shows captcha to the user, you can dynamically generate obfuscated JavaScript functions(i think the best way 5 or 10).
For example, one function(or 3)) ) can set cookies with pregenerated hash(server returns it)(from real value of the captcha), other functions must realize server side algorithm to check value which user's typed. I can say that it works for 100%, because it is very hard to parse dynamically javascript + we set user cookies on client side(It is very hard for Bots's to find out where and how you set and check cookies), by using JavaScript.

Generation of Email Validation Links

For a Web Application I'd like to generate an email validation link and send it to the user. Like on many public websites, the user should click it to validate his email address. Looks similar to this:
http://www.foo.bar/validation?code=421affe123j4h141k2l3bjkbf43134kjbfkl34bfk3b4fkjb43ffe
Can anybody help me with some hints about the proper generation of those validation tokens? Googling best practices turned out to be more difficult than I though it would be. The links should:
... not require the user to log in first.
... not reveal any login credentials to keep the application secure
... allow me as a developer to efficiently validate the token. I'm pretty sure I need a way to extract the user identifier out of the code to meet this criteria. Don't I?
Furthermore, would you go for a random code, which is saved somewhere, or a generated code which I can recalculate for validation?
Thanks for any replies!
Matthias
P.S. I'm working with ASP.NET 3.5, in case there's an out-of-the-box feature to perform this.
Some suggestions to get you started:
Use GUIDs
Use some sort of salted hash (MD5, SHA1, etc)
Use a random string of characters (the more characters the less likely you'll have collisions)
Store it in a database temporarily, and timestamp it so that it expires after a certain period of time
The simplest way to do it is generate a GUID, store that in the database tying it to their user account and then give them a time-frame within which to click a link with that GUID in.
That validates they are the correct person without making the URL calculable whilst making it resistant to dictionary style attacks.
I construct the hash in a way that can be re-created:
code = MD5( my_hash + user_email + register_timestamp )
Then send a link to http://example.com/validation/?code = 4kj34....
Validation does a lookup like:
SELECT id
FROM users
WHERE
MD5( CONCAT( my_hash, user_email, register_timestamp ) ) = code
AND activated = 0
If you get a single result, update their 'activated' field and sign them in. You can also do some math on their 'register_timestamp' field for a poor man's TTL
I would probably use a Guid. Just create a Guid (by calling Guid.NewGuid()), store it as the validation token for that user, and include it in the validation link.

Resources