ASP.NET Impersonation design - asp.net

This is my ASP.NET authentication operation.
private void LoginButton_Click(Object sender,
EventArgs e)
{
string userName = txtUserName.Value;
string password = txtUserPass.Value;
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(3), chkPersistCookie.Checked,
userName + "#ticket");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect == null)
strRedirect = "MyAccount.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}
I have User table in my db where all credentials are saved. Using ValidateUser method I am doing credentials validation. Also I have three type of users: Member, Moderator and Administrator. Each type of members has unique functionality. Lets say I have A, B and C T-SQL stored inside in my db.
What should I to to let for:
Member execute only A query.
Moderator execute A and B.
Administrator execute A,B and C.
Of course, I can manage execution from Web app, but I am not sure how safe it is. Technically I can execute similar query outside of App, which gives access to all db data. I want somehow combine Web App login and Db access as well.
Thanks!

If these queries are going to come from the web app, I think you would want to manage the code side that invokes the procedures.. you could maintain a list of urls in your database, assign roles, and give these roles access to specific urls. These urls would dictate what queries a user could execute...
then in your code you could assign custom attributes to limit access to them....

http://msdn.microsoft.com/en-us/library/ff647396.aspx

Related

How to access multiple tables from a SELECT FROM in ASP.NET with SQL Server?

I have this project I am working on for an assignment, and I have a question working with ASP.NET and SQL Server. I have a login page that kinda works, but there are two tables that I need to get data from - users (subscribers) and admin page but am unsure how to access both of them as I can only access one.
public void login(Object src,EventArgs e)
{
get_connection();
try
{
connection.Open();
command = new SqlCommand("SELECT * FROM subscribers WHERE Email = #Email AND Password = #Password", connection);
command.Parameters.AddWithValue("#Email", loginName.Text);
command.Parameters.AddWithValue("#Password", loginPass.Text);
//command = new SqlCommand("SELECT * FROM admin WHERE Email =#Email and Password = #Password", connection);
//command.Parameters.AddWithValue("#Email", loginName.Text);
//command.Parameters.AddWithValue("#Password", loginPass.Text);
reader = command.ExecuteReader();
I commented out the admin part because when I include it, only admin username and password is accepted and not subscribers. What would I need to do to fix this?
The "admin part" causes you to only get records from the admin table because you're destroying and recreating your SqlCommand object. You'll need to create a new command in a different variable and read from it separately. There are ways to get multiple recordsets in the same call but I don't recommend it in this case.
That out of the way... Normally I'd expect to see a single users table with permissions/roles granted elsewhere. Consider something like the out of the box ASP.NET membership provider to take care of these implementation details for you:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-the-aspnet-membership-provider

session variable for username

Hey I am creating a forum where users can login and post ocmments in a forum, I want the username as a session variable so I can get it when they post a comment and insert the username in the db and also to display a hello user message.
Below is my login code:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
localhost.Service1 myws = new localhost.Service1();
ds = myws.GetUsers();
foreach (DataRow row in ds.Tables[0].Rows)
if (txtusername.Text == System.Convert.ToString(row["username"]) &&
txtpassword.Text == System.Convert.ToString(row["password"]))
{
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false);
}
else
Label3.Text = "Invalid Username/Password";
}
Do I declare the session variable here?
Like:
Session["username"] = "username";
Also not sure what to type to get the value username from the db
Thanks
You don't need to use a session. Once you call the FormsAuthentication.RedirectFromLoginPage method, inside the target page you could access the currently connected user from the authentication cookie that was emitted by this method using User.Identity.Name.
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name;
// ...
}
}
To learn more about how Forms Authentication works in ASP.NET I invite you to read the following article.
You are already using forms authentication (FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false)) which is great. Consequently, you don't need to store the username is session as it's already available via User.Identity.Name, as Darin noted.
I have written two tutorials on forms authentication you might find useful:
An Overview of Forms Authentication
Forms Authentication Configuration and Advanced Topics
Additionally, consider using Membership. Membership is a subsystem built into ASP.NET that handles user accounts and provides an API for creating accounts, deleting accounts, etc. In short, you don't have to write all that code yourself. And with the login Web controls, creating new accounts, signing users in, resetting passwords, and so on, are all quite simple and involve zero to little code. For more information see my Membership tutorials.
Happy Programming!

Create User using Membership.CreateUser

I used the following to create new users using SqlMembershipProvider. While trying to create new users using CreateUserWizard, it throws exception 'The username is already in use' even though there is no any user exists and also new row is creating successfully with this username and password in my table.
MembershipUser newUser = Membership.CreateUser(createWizard.UserName, createWizard.Password);
If i hard code the value of username and password no exception occurs.
Can any one tell me the reason why it throws the exception when using CreateWizard?
MembershipCreateStatus status;
var user = Membership.CreateUser(login, password, email, null, null, true, out status);
Try this.
Check in your Membership.dbo database if this user exists.
SELECT *
FROM aspnet_Users
WHERE (UserName = 'YourUserName')

How to provide different pages on login for different users?

I'm working on web application which has a database
UserName|Password|UserType
Anil|Anil|Manager
ghouse|Ghouse|Admin
raghu|raghu|User
Now my task is to provide each user their own page on login...They all have a same login page.
I tried this code it's working fine for two users. What to do if I have more than two users?
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DebitCareBankApp;Data Source=SSDEV7-HP\\SQLEXPRESS");
string cmdStr = "select LoginType from Login where UserName='" + TxtUsername.Text + "' AND Password = '" + TxtPassword.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
Object TypeUser = cmd.ExecuteScalar();
con.Close();
if (TypeUser != null)
{
LblError.Visible = false;
LblError.Text = "";
if (TypeUser.ToString() == "Manager")
Response.Redirect("~/CallingAgents/CallingAgents_Login.aspx");
else
Response.Redirect("~/UserRegistrationForm.aspx");
}
else
{
LblError.Visible = true;
LblError.Text = "Invalid Credentials Entered, Try again";
}
I think you should create a common class where insert your user type on successful login.
In that common class redirect it to respective page.
On successful login:
Response.Redirect(clsCommon.GetDefaultPage(userType));
your commaon class code:
public static string GetDefaultPage(string userType){
//Default Redirects
Dictionary<string, string> userInfo = new Dictionary<string, string>(){
{"Manager","~/ManagerLogin.aspx"}, {"Admin","~/AdminLogin.aspx"},
{"User","~/UserLogin.aspx"}
};
return userInfo[roleName];
}
If you are using struts then you can redirect to different pages depending upon some Id. In actionforward you can achieve so. Or you can get some values from the url and try to redirect it
A simple way would be to use the Login-control and provide event handlers for the Authenticate event and the LoggedIn event. But i think it would be worth while for you to check out the capabilities of the asp.net membership system.
I assume you are not using Membership provider and make your login functionality by hand.
I do not fully understand the purpose of this customization. It make no sense for me. But there are multiple solutions for you:
convert the login page (aspx) into a user/custom control (ascx) and put in into different pages - simple, quick but not fully transparent, more info ScottGu
use IIS URL-Rewrite engine to provide multiple entry-points (urls)
to the same login page - clear, recomended, more info ScottGu
With first scenario you need to check UserType for credentials given by the user and confront it with page Url (aspx). In the second scenario, you need to obtain Request.RawUrl which contain base Url and make simple case.
Make use of sessions.
For a workaround, you can follow this:
+provide the same login page.
+Ask for username and password.
+use a drop down for selecting the usertype (ie Admin or Manager or User).
So based on the selection from drop down list you process the request.
I hope this helps.

Asp.Net 4 Response.Cookies.Add does not add cookie to users machine

I am trying to setup a basic Form Authentication using ASP.NET 4.
I know my validation code (code that checks if the username and password is correct) is working because after if the user enters invalid information the ReturnLable tells them so. However if they enter the correct information, they are redirected to the restricted page with a 403 – Forbidden error. When I check the shell:cookie path no cookie has been written even though I added it to the collection “Response.Cookies.Add(cookie);”
protected void Submit_Click(object sender, EventArgs e)
{
Email.Text = Email.Text.Trim();
Password.Text = Password.Text.Trim();
if (IsValid(Email.Text, Password.Text)) //user exists
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
Email.Text,
DateTime.Now,
DateTime.Now.AddMinutes(50),
RememberMe.Checked,
"user",
FormsAuthentication.FormsCookiePath);
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
Response.Cookies.Add(cookie);
}
else
{
ReturnLable.Text = "<font color=red> Username/Password Incorrect Please Try Again </font>";
ReturnLable.Visible = true;
}
From this MSDN article:
If you do not set the cookie's expiration, the cookie is created but
it is not stored on the user's hard disk. Instead, the cookie is
maintained as part of the user's session information. When the user
closes the browser or if the session times out, the cookie is
discarded.
Thus, a cookie could be successfully set, alive and well in the browser, but have no corresponding file in the "cookies" folder on the hard drive.
make sure that Enable anonymous access is disabled on IIS and Integrated Windows security is enabled

Resources