Show Logged In User Name in redirect.aspx Page - asp.net

I'm a complete stranger to ASP.NET. But, I've had a project to do using it & faced a problem.
It is :
I have a login.aspx File - Where Users provide login User name & Password
If Login details (match Data Base) OK then User automatically redirects to logged_in.aspx.
There's a label (lbl_show) in redirected logged_in.aspx.
I need to show Logged in Username in it.
I read bunch of articles & came with nothing because of my lack of understanding so please help me.

se session variables in order to pass any value from one page to another.
Assign the Username value to the session variable and use it in your logged_in page as follows:
// In login page
Session["UserName"] = txtUserName.text;
//In logged_in page
label1.text = Session["UserName"];
Also refer the following link for State Management:
http://www.codeproject.com/Articles/492397/State-Management-in-ASP-NET-Introduction

You need to set an Authentication Cookie. It's easy and will allow you to leverage ASP.NET functionality easily (many built-in controls and also user-access control). I detail how in this SO post:
Using cookies to auto-login a user in asp.net (custom login)

The problem with the code
// In login page
Session["UserName"] = txtUserName.text;
//In logged_in page
label1.text = Session["UserName"];
Is casting is missing it should be
label1.text = Session["UserName"].ToString();
Edit 1
As Session contains object and if you have something other than object then you will have to explicitly cast it in your require type.
Suppose you have array in you Session then you will have to cast it back to array.
String[] Names={"abc","def","ghi"};
Session["NamesCol"]=Names;
Then if you want to use it you will have to cast it as follow
String[] NewNames=(string[])Session["NamesCol"];

Related

Preventing scripted POST in ASP.NET MVC

In my ASP.NET MVC project, user can save a form on screen which makes HTTP POST request to server.
How can I prevent client to send automated HTTP POST's to server. Is there any builtin way on IIS or web.config to block unusal request rates?
For example a setting like, "based on Session ID, request count in 1 minute cannot exceed 30" could be helpful.
Captcha control is not a good option for me. Because there are many save options on screen, setting captcha for each of them will be useless.
Not quite what you asked for, but you can use session variables to limit a form from being posted unless the form is first requested, and protect against being submitted multiple times.
On your form page, generate a random number:
Random rnd = new Random();
int key = rnd.Next(100000, 999999);
Create a session variable with this number as the name, something like this:
Session["key_"+ key.ToString()] = true;
In your form add a hidden field with this number:
<input name="key" type="hidden" value="#key" />
Upon form post get the hidden field value and check that the session variable exists. Then remove the session variable so the form cannot be resubmitted:
int key = 0;
int.TryParse(Request.Form["key"] ?? string.Empty, out key);
if (Session["key_" + key.ToString()] == null)
{
//invalid post, take some action
//best to return the user to the form and give them another chance
//in case it was legitimate, eg. session timed out
}
else
{
Session.Contents.Remove("key_" + key.ToString());
}
You can use a mvc attribute called AntiForgeryToken on your post action method, It generates a encrypted value and a salt used to verify if your post is authentic.
See this link
https://msdn.microsoft.com/en-us/library/dd470175(v=vs.118).aspx

How to set the current user for WebPartManager?

From what I've been reading, the following code should first ensure that a MembershipUser record exists for "ArthurDent", then set "ArthurDent" as the current user, and finally assign his MembershipUser record to the variable mUser.
if (Membership.GetUser("ArthurDent") == null)
{
Membership.CreateUser("ArthurDent", "thisisapassword");
}
FormsAuthentication.SetAuthCookie("ArthurDent", true);
MembershipUser mUser = Membership.GetUser();
Instead, the variable mUser remains null.'
My goal is to programmatically set the current user to a valid record so that I can set a WebPartManager.DisplayMode on a page that started erroring out when I added BlogEngine to my web site.
This problem generally occurs when the application breaks a rule defined in the web.config file. For instance I ran your code in my local environment using Windows Authentication and CreateUser at first failed because the password string was of insufficient length. I padded the password with additional characters and was able to create user with the supplied code. Check the section to examine password prerequisites.
Upon first examination this looks like a configuration problem.
The answer is that BlogEngine actively suppresses the normal workings of Page.User.Identity, which Membership.GetUser() retrieves. When I replaced FormsAuthentication.SetAuthCookie with the following code from BlogEngine...
Security.AuthenticateUser("ArthurDent", "thisisapassword", true);
... it authenticated Arthur and logged him in.

Forms Authentication Not Validating User properly

I have this code when to sign in User , that string sUserData is properly set.
Dim sUserData As String = HttpContext.Current.Request.Cookies("UserID").Value & "|" & HttpContext.Current.Request.Cookies("UserName").Value & "|" & HttpContext.Current.Request.Cookies("UserEmail").Value
Dim fat As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
HttpContext.Current.Session("UserID"), DateTime.Now, _
DateTime.Now.AddDays(6), True, sUserData, _
FormsAuthentication.FormsCookiePath)
HttpContext.Current.Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat)))
Then I have code where I check if the user if signed in in a Shared (static) method in a Public Class like this :
If HttpContext.Current.User.Identity.IsAuthenticated Then
EndIf
And that works just fine , but if I put the same line in Page_load instead of a Shared Method of a class it will never go into this If statement
If HttpContext.Current.User.Identity.IsAuthenticated Then
EndIf
Why is this happening , and is there some way to re-write this to work in the code-behind Page_Load instead of having to put it in a class ,The class is used in a header to allow access to certain pages - so that works fine. But I need another way of authentication of user on Default page to change labels and buttons based on weather the user is logged in or not , and this can not be done in a class.
Have you tried putting the page event overrides into an actual page event override (i.e. OnLoad) instead of the Page_Load event hook implementation? More performant (fewer layers of invoke), slight difference in life-cycle which may suit your needs and may distill the cause of these symptoms.
There may be a sequencing issue / race condition if the context of the static method call and the Page_Load, I think Wiktor Zychla pointed you in the direction of fiddler already.

ASP.NET / VB.NET Check If a (different) User IsInRole

I have an ASP.NET application on our company's intranet. And a funky security requirement.
I need to check to see if a given username is in a certain role. I cannot use
Page.User.IsInRole("MyDomain\MyGroup")
because
Page.User.Identity.Name
Returns an empty string. Because of some lovely specifications for this program, I have to keep anonymous access enabled in IIS. Seems to rule out any page.user.identity stuff.
So I did find a way to (at least) get the current user (from System.Environment.UserName), but I need to bounce it against the domain group to see if they're in it. Or, better yet, get a list of users within a given domain so I can check myself. Something like...
Dim UserName as String
UserName = System.Environment.UserName
If User(UserName).IsInRole("MyDomain\MyGroup") Then
MyFunction = "Success"
End If
-OR -
Dim GroupUsers as String()
GroupUsers = GetDomainUserNames("MyDomain\MyGroup")
Anybody have any ideas?
You can call IsUserInRole from the Roles static class. Here is a sample and some reference materials.
Roles.IsUserInRole(username, rolename);
link: http://msdn.microsoft.com/en-us/library/system.web.security.roleprovider.isuserinrole.aspx

Storing multiple values in cookies

I have very large website which uses a lot of cookies. There are approx. 14 different cookies are there. I have different cookies for each item. When a user surfs the site they will have 14 cookies in their browser. I do not want this.
I want a single cookie for my site that will have 14 items and I can add,edit and delete them. I tried many ways but I am not able to do this.
I need to put some run time cookies as well save the user name in cookie. After the user logs in I want to save their personal site address in it. Eventually I want both the user name and personal site address both. I want to save user name before and then when user goes to his personal site then i will store personal site name run time.
Does any one have an idea how I could do this?
Matthew beat me to it, but yes, see the ASP.NET Cookies Overview...
To write and read a single cookie with multiple key/values, it would look something like this:
HttpCookie cookie = new HttpCookie("mybigcookie");
cookie.Values.Add("name", name);
cookie.Values.Add("address", address);
//get the values out
string name = Request.Cookies["mybigcookie"]["name"];
string address = Request.Cookies["mybigcookie"]["address"];
There is a section in the ASP.NET Cookies Overview that discusses how to implement multiple name-value pairs (called subkeys) in a single cookie. I think this is what you mean.
The example from that page, in C#:
Response.Cookies["userInfo"]["userName"] = "patrick"; //userInfo is the cookie, userName is the subkey
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString(); //now lastVisit is the subkey
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
EDIT: From the Cookies Overview (emphasis added):
Modifying and Deleting Cookies:
You
cannot directly modify a cookie.
Instead, changing a cookie consists of
creating a new cookie with new values
and then sending the cookie to the
browser to overwrite the old version
on the client.
Modifying and Deleting Cookies: You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.

Resources