role based authorization with window authentication in asp.net - c#

I have to create a role based application in which i have three roles admin,manager and user. In my application i have three different folder in which i have to check those role. What i want is when i enter credential in my login page first it will check whether user is authorized or not and if not then redirect to the error page. If authorized then check its roles and give access to the specified folder.
this is my login page code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
String queryread = #"Select * from Login where UserName = '" + tbUserName.Text.ToLower() + "' and Password='"+ tbPassword.Text.ToLower() +"'";
SqlConnection con = new SqlConnection();
SqlDataReader read;
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["BartConnectionString"].ConnectionString;
SqlCommand readdata = new SqlCommand(queryread, con);
try
{
con.Open();
read = readdata.ExecuteReader();
Boolean flag = false;
while (read.Read())
{
String UserName = read["UserName"].ToString().ToLower();
String password = read["Password"].ToString();
if (tbUserName.Text.ToLower() == UserName)
{
if (tbPassword.Text.Trim() == password)
{
Session["UserID"] = UserName.ToString();
flag = true;
}
}
}
if (flag)
{
Response.Redirect("~/Supervisor/Form.aspx", false);
}
else
{
Response.Redirect("~/Error.aspx",false);
}
}
catch (Exception ex2)
{
Response.Write("Error");
}
finally
{
if (con.State == System.Data.ConnectionState.Open)
con.Close();
}
}
in this i check the authorization for the user now i also want to check which role this user have what changes i have to make in this code to check roles also
In my sql i have table login which have
UserID
UserName
Password
RoleID
what changes i have to make in my web.config file. what change i have to make in my login page to check role. I guess my question is clear to you guys.
Thanks in advance

As I said in the comment above I wouldn't accept this code into a project I was managing and you should be very careful about how you implement user authentication in an application. I would start by having a good read of this document on MSDN:
Security Basics and ASP.NET Support
Overview of Forms Authentication
Forms Authentication Configuration and Advanced Topics
Once you have that in place you can have a look at Roles in this article:
Authenticating Users with Forms Authentication
There is a lot to take in here but reading through these will give you a good base to start from.
Even though you want to use Windows Authentication I would still read the above linked articles as they will give you a lot of useful information about how authentication work in general. To use Windows Authentication with ASP.NET read this:
Windows Authentication in ASP.NET

Related

Secure login method in ASP.NET MVC

I'm currently working on the login system of my WebApp, which I'm developing in ASP.NET MVC. I am currently using the .NET Framework 4.8.x. Now I have developed the UI and my backend is running. This allows the user to log in and out without any problems. But my question now is whether my way of working is safe?
This is what my login function looks like:
Note: Currently, I am saving the password as it is for testing purpose but later i will change it as a hashed one with salt added to it.
String mycon = "my-connection-string";
SqlConnection scon = new SqlConnection(mycon);
String myquery = "select * from loginDetails where uName=#uName and paswrd=#paswrd";
scon.Open();
SqlCommand cmd = new SqlCommand(myquery, scon);
cmd.Parameters.AddWithValue("#uName", lc.userName);
cmd.Parameters.AddWithValue("#paswrd", lc.password);
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
Session["username"] = lc.userName.ToString();
return RedirectToAction("Index", "Home");
}
else
{
ViewData["Message"]= "Invalid Username or Password";
}
scon.Close();
return View(lc);
This is what my logout function looks like:
if (Session["username"] != null)
{
Session.Clear();
Session.RemoveAll();
Session.Abandon();
}
return View();
Do I have any mistakes here? It doesn't seem very safe to me if only the username is checked by the server. Wouldn't it be safer if I used a SessionID and it expired after 24 hours for example? Unfortunately I don't know how to do that. I know how the automatic logout works via session-timeout. But I think the SessionIDManager would help me a lot. However, I don't use an entity framework and therefore I can't give the class SessionIDManager a context instance.
To authorize the user I use a filter. It looks like this:
public class Authorize : System.Web.Mvc.ActionFilterAttribute, System.Web.Mvc.IActionFilter
{
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
{
if (HttpContext.Current.Session["username"] == null)
{
filterContext.Result = new System.Web.Mvc.RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary
{
{ "Controller", "Login"},
{ "Action", "Index"},
});
}
base.OnActionExecuting(filterContext);
}
}
Does anyone have an improvement suggestion for me?
Is it safe to use the session variable for authorization?
You can use login with model (secure method) ;
public ActionResult Login(string username, string password)
{
// LoginDetails -> Your Model Name && db -> Your Database Context Name
LoginDetails loginDetails = db.LoginDetails.Where(item => item.username == username && item.password == password).FirstOrDefault();
if(loginDetails == null)
// Login Failed
else
// Login Successful
}

Access Login Control from Different Page

I have a website in C# where users are authenticated to a SQL database via login control. Everything is working fine currently as I'm using the web.config to to direct to the Login.aspx page if the user isn't logged in. What I would like to do though is access the login controls from another page but additionally pass another parameter.
So for example...
The web.config has the following:
<authentication mode="Forms">
<forms defaultUrl="~/Default.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="20"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
The Login.aspx page looks like the following
protected void LoginControl_Authenticate(object sender, AuthenticateEventArgs e)
{
bool authenticated = this.ValidateCredentials(LoginControl.UserName, LoginControl.Password);
if (authenticated)
{
FormsAuthentication.RedirectFromLoginPage(LoginControl.UserName, LoginControl.RememberMeSet);
}
}
private bool IsAlphaNumeric(string text)
{
return Regex.IsMatch(text, "^[a-zA-Z0-9-]+$");
}
private bool ValidateCredentials(string userName, string password)
{
bool returnValue = false;
if (this.IsAlphaNumeric(userName) && userName.Length <= 25 && password.Length <= 50)
{
string sqlConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection sqlConnection1 = new SqlConnection(sqlConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = ("ValidateUser");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("LoginName", userName.Trim());
cmd.Parameters.AddWithValue("LoginPass", HashData.HashString(password.Trim()));
cmd.Parameters.AddWithValue("Type", "Read");
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
if (cmd.ExecuteScalar() == null)
{
returnValue = false;
}
else
{
returnValue = true;
}
}
}
}
return returnValue;
}
}
Now what I would like to do is utilize the same login control across other pages so that I can see if the same user is logged in but pass a different "Type" parameter such as "Edit".
So the way I would like it to work is this... The users accesses the site and is redirected to the Login.aspx page. The login control runs my stored procedure verifying they are "Read" type and redirects them to the Default.aspx. From here a user can click an Edit button. Once they do, the same login control would check if they have "Edit" rights by running the same stored procedure but instead passing that as the "Type" parameter. At this point if the results are false the user would be prompted to login if their current rights don't allow it, or the page would just load if the current user has those rights. Is there a way to do what I"m looking for or would I need to just user either multiple login controls or different folder structure and do this all with web.config?
What you can do is create a Master page and put the Login Control in the Master page. Have each page that you want to be able to authenticate inherit from the Master page, which would give it access to the Login Control.
Problem solved...
What I ended up doing was to let the login control authorize a user with the lowest level rights. When a user attempts to access a page that requires higher rights, I'm first checking if
if (User.Identity.IsAuthenticated == true)
If true, then I run a new query that checks if User.Identity.Name is of the correct "Type".

Forms Authentication - Accessing User Data

I’m having some difficulty understanding how to access specific user data while using Forms Authentication.
I have already set up Forms Authentication for a User and an Admin.
When a User tries to log in, here is the code that runs:
protected void buttonLogIn_Click(object sender, EventArgs e)
{
string email = TextBoxEmail.Text.Trim();
string password = TextBoxPassword.Text.Trim();
UserType userType = UserType.User; //temporary value
string firstName = string.Empty;
string lastName = string.Empty;
bool success = DBAppLayer.AuthenticateLogIn(email, password, out userType, out firstName, out lastName);
if (success == true)
{
Session.Add("email", email);
Session.Add("firstname", firstName);
Session.Add("lastname", lastName);
switch (userType)
{
case DBDataLayer.UserType.User:
FormsAuthenticationUtil.SetAuthCookie(email, "User,", false);
Response.Redirect("~/User/UserDashboard.aspx", false);
break;
case DBDataLayer.UserType.Admin:
FormsAuthenticationUtil.SetAuthCookie(email, "Admin", false);
Response.Redirect("~/AdminArea/AdminDashboard.aspx", false);
break;
}
}
else
{
labelError.Text = "Bad username/password.";
}
}
This successfully redirects a User to their dashboard. Now when the User is in /User/UserDashboard.aspx, I want to display the User’s profile information that is stored in the database, such as the User’s job and age.
The problem is, I’m not sure how to access this specific User’s data in UserDashboard.cs. Do I need to create an Authentication Ticket? If so, would I do this in the login page?
Any links or suggestions would be appreciated.
It looks like your call to FormsAuthenticationUtil.SetAuthCookie passes in email as the user id when you create the authentication cookie. In your user dashboard page, the User.Identity.Name field will give you back this same email address. Use that value to call your database and get the user's profile.
You are also storing the email address in the Session so you could get it from there as well.

Login using Facebook Problem after logging out

I am using facebook sdk and facebook connect for integrating fb into my site using asp.net and c#. The user can login using the code successfully. The problem that I face is that whenever a user is logged in thru fb; if the user logs out from the facebook's site and then tries to login through my site using fb connect, it gives error: The session is invalid because the user logged out.
I should again provide the facebook connect button to log in as it does initially but it gives error. The code used is shown below:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (ConnectAuthentication.isConnected())
{
Facebook.Session.ConnectSession _connectSession = new Facebook.Session.ConnectSession(ConfigurationManager.AppSettings["ApiKey"], ConfigurationManager.AppSettings["AppSecret"]);
if (!_connectSession.IsConnected())
{
lblStatus.Text = "Please sign-in with Facebook.";
}
else
{
Facebook.Rest.Api api = new Facebook.Rest.Api(_connectSession);
Facebook.Schema.user user = api.Users.GetInfo();
string fullName = user.first_name + " " + user.last_name;
lblStatus.Text = fullName;
}
}
else
{
lblStatus.Text = "Please sign-in with Facebook.";
}
}
}
When a user logs out the session is invalidated. You need to have the user log in again. If you don't want to do that then please request the "offline_access" extended permission during authentication. This way the user does not have to be logged-in.
FYI, you will have to move to OAuth before September 1st 2011. Facebook will ONLY support OAuth after that.

ASP.NET Forms Authentication authenticates in localhost server, but not on the web server

I've been implementing the Forms Authentication in ASP.NET with C# (v3.5).
I created a simple login form, when the users' email & passwords are stored in my SQL db.
When I login in my localhost, everything works just fine, but when I published the project and uploaded it on to my production web server, things got a little bit wierd for me.
The HttpContentxt.Current.User.Identity.IsAuthenticated variable return false, even if the login was successfull (and again, in localhost everything works fine).
This is the following login button click code (I'm using my own DataAccess, ignore it's irrelevant code):
protected void btnLogin_Click(object sender, EventArgs e)
{
Page.Validate("Login");
if (Page.IsValid)
{
string email = txtEmail.Text;
string passwd = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5");
WebFactory.DataAccess.Users.Data userData = new WebFactory.DataAccess.Users.Data(ConnectionString);
userData.Load(new WebFactory.DataAccess.Users.Item[] {
new WebFactory.DataAccess.Users.Item(WebFactory.DataAccess.Users.Columns.Email, email),
new WebFactory.DataAccess.Users.Item(WebFactory.DataAccess.Users.Columns.Password, passwd)
});
if (userData.HasData) // Login Success
{
if (!cbRememberMe.Checked)
{
FormsAuthentication.SetAuthCookie(userData.Id.ToString(), false);
}
else
{
FormsAuthentication.Initialize();
DateTime expires = DateTime.Now.AddDays(20);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
userData.Id.ToString(),
DateTime.Now,
expires,
true,
String.Empty,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authCookie.Expires = expires;
Response.Cookies.Add(authCookie);
}
lblStatus.Text = "";
if (Common.QS.HasRefUrl)
{
Response.Redirect(Common.QS.RefUrl);
}
else
{
Common.UserTools.RedirectLoggedInUser(userData.Id);
}
}
else // Login failed
{
lblStatus.Text = "Email or password is wrong. please try again."
}
}
}
Thanks for all helpers, and sorry for the english mistakes.
Thanks all, I solved the problem.
I just needed to enter a name attribute in the <forms> clause and everything works perfectly now.
Thanks again!
Try checking the Forms Authentication Configuration in your web.config. Specifically the domain and path variables. The domain should match the domain of your website and the path should match the application folder name. You probably won't have one of these, so just set it to "/"
You can also set up tracing to make sure that the cookie is actually being read by the application.

Categories