Mike Marks
Mike Marks

Reputation: 10139

How do I restrict direct access to an ASP.NET web page?

The idea is I'll have a promo code system, so when the user is on "EnterPromoCode.aspx", and they enter a valid promo code, the website will direct them to "PromoDeals.aspx". But, I don't want anyone to simply be able to type in "PromoDeals.aspx" and go to it.

I was thinking of passing some sort of query string parameter to PromoDeals.aspx to validate where the user was coming from (via the Page_Load method), but I'm not sure exactly if there is a straight forward way to do this. Any advice?

Upvotes: 0

Views: 2679

Answers (2)

JustAndrei
JustAndrei

Reputation: 859

Basically, the idea is as follows:

  1. One of your pages checks whether the user knows the "secret". This is kind of authorization.

  2. Some other page(s) works only if the user has been authorized.

It's obvious that information about successful authorization should be stored in some place, which is shared between various pages. There are a lot of ways to share information between pages.

A) Session. Once the user has submitted the correct promo code, your authorizing page stores something in the Session collection. That could be just a flag indicating the fact of successful authorization, or that could be the promo code - if you would need its value later.

Any other page can check what's stored (or not stored) in Session in the Page_Load handler and decide what to do then: continue or render an error, or redirect to another page. Note: sessions expire. What's you store there is forgotten when the session ends.

B) Cookies. This way your information lasts as much time as you want - you set the expiry date. But since it's stored in the user's browser, there are disadvantages: the browser may refuse to store your cookies; the user may clear them.

C) Database. If you want to make sure the user is authorized once and for ever, store this info in the database.

Upvotes: 3

Lars Anundskås
Lars Anundskås

Reputation: 1355

You could require either post or get (or support both) on PromoDeals.aspx.

If using post, in your Page_Load of PromoDeals.aspx, you can check Request.Form["PromoCode"] and validate it, if it's not valid, you can do a Response.Redirect back to EnterPromoDeals.aspx.

Similarly if using get, check Request.QueryString["PromoCode"] and validate it (check in your db or whatever to see if its a valid promocode, if not, Redirect the user away from the page.

The validation of the promo code could also be done in EnterPromoCode.aspx, if user enters valid promo code, you set a session variable;

Session["PromoCode"] = Request.Form["PromoCode"].ToString();

If this was set (a valid code was entered), redirect to PromoDeals.aspx. And then, on PromoDeals.aspx, you would redirect the user away if this session var ain't set.

Upvotes: 3

Related Questions