RBAC in asp.net - asp.net

I have a users table in my sql server 2008 which has
username, password, email,first name, last name and user group.
I want to display my website controls specific to that user groups once the user logs in.
Could you please help in this issue.

You can assign user's user group is a session variable at the time of log in. Now you can set (may be on page_load) your pages's controls visibility upon that value.
Something like this,
If(Session["UserGroup"] == "1")
{
ControlID.Visible = true;
}
else
{
ControlID.Visible = false;
}

Related

how to prevent user login with same account in ASP.NET MVC

I want to prevent multiple login for user with same username and password . Example :
User A login with account "A", Session["AccountA"] is create ( about 30 minutes ) . After user B login with account "A" ,Session["AccountA"] is create and Session["AccountA"] of user A timeout .
Yes, it is possible (although may not be as great an idea as you are thinking). Here's one way to do it:
When the user signs on, store a value in Application state that binds his session ID to his user ID.
var context = HttpContext.Current;
var lookup = String.Format("Session_{0}", userID);
Application.Lock();
Application[lookup] = context.Session.SessionID;
Application.Unlock();
When a user requests a page (and is not signing on) check to see if the binding is correct. If not, kill the session.
var context = HttpContext.Current;
var lookup = String.Format("Session_{0}", userID);
var sessionID = Application[lookup] as string;
if (sessionID != context.Session.SessionID)
{
context.Session.Abandon();
var c = new HttpCookie(FormsAuthentication.FormsCookieName,"DELETED");
c.Expires = System.DateTime.Now.AddDays(-2);
context.Response.AppendCookie(c);
context.Response.Redirect("~/logout.aspx");
}
When a user attempts to access a page, but has the wrong session ID, his session will be killed.
The trick here is... your Application state will keep growing as users sign on. You will need to devise some means of detecting when users have signed off and cleaning it up, or you will need to recycle your AppPool on a regular basis.

How can i keep users logged in when they return? [duplicate]

HI
I am using asp.net mvc with asp.net membership.
I want to have a checkbox that if clicked keeps the users signed in for 2 weeks(unless they clear their cookies).
So I know their is
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie)
but I don't know how to set it up for 2week retention.
I rewrote most of the membership stuff. So I don't use stuff like Create() and VerifyUser().
Add a hash key or a random string to both the cookie and the database (both the same key). If the cookie and database value are the same, when the user starts a new session, sign him/her in again. When the user reaches the two weeks, remove the secret key from the database using a cronjob (Unix) or scheduled task (Windows).
Warning: Do not rely on the cookie expire date, since people can hack their browser.
Rule: NEVER, EVER trust ANY of your users!
You can set the global session timeout (the value is in minutes) in web.config eg.
<system.web>
<authentication mode="Forms">
<forms timeout="20160"/>
</authentication>
</system.web>
This will be for all authenticated users. If you want to use the 'Remember Me' functionality then you will need to write your own code to set the cookie/ticket. Something like this (taken from here):
protected void Page_Load()
{
if (Request.Cookies["username"] == null || Request.Cookies["username"].Value.ToString().Trim() == "")
{
Login1.RememberMeSet = true;
}
else
{
Login1.UserName = Request.Cookies["username"].Value.ToString().Trim();
Login1.RememberMeSet = true;
}
}
protected void RememberUserLogin()
{
// Check the remember option for login
if (Login1.RememberMeSet == true)
{
HttpCookie cookie = new HttpCookie("username");
cookie.Value = Login1.UserName.Trim();
cookie.Expires = DateTime.Now.AddHours(2);
HttpContext.Current.Response.AppendCookie(cookie);
Login1.RememberMeSet = true;
}
else if (Login1.RememberMeSet == false)
{
HttpContext.Current.Response.Cookies.Remove("username");
Response.Cookies["username"].Expires = DateTime.Now;
Login1.RememberMeSet = false;
}
}
Just use a simple cookie with 2 weeks expiration date.
Have you seen this?
http://forums.asp.net/t/1440824.aspx
Along similar lines to what Koning has suggested.
You can not use a session method to keep your users logged in, since browsers delete the session cookies when the browser is closed.
Do what user142019 offered and set the session's IdleTimeout parameter very short, up to 15 min. When the server receives any request from the browser, first check the session if it's alive. if not, try to get the cookie. If the cookie and database value are the same and not expired, assign it to the (new) session and return the response.
You can use onBeforeUnload listener to send a logout request when the user leaves your site. If logged out, delete the cookie and the db record, if not - assign a new hash for the next auto login and refresh that hash again when the user retunes to your website. You can also keep track of IP and the browser and link them to the hash in your db.
So, in case if the cookie is used with another browser or IP, and the hash code is valid, you can force them to login again.

Do action if button clicked for 3 times

I want to do some action if button clicked for 3 times. Just like if users enters a wrong password for 3 times the page the page must be redirected to another page or something.
How to do action in ASP.NET C# if button clicked for 3rd time?
To check if a user has taken an action fox "x" times you need to store it somehwere. If you're using a relation database you could for example call a table LoginAttempts and there you store all unsuccesfull logins. When you have that table you can build your logic against it.
I'd use a session variable.
Another solution could be having a column in the users table named LoginAttempt(int)(default 0), how I would use that column is
Let's say you have a table in your databese called TblUsers with these columns
Id,
UserName,
Password,
LoginAttempt.
And let's say you have two TextBoxes on your Login.aspx page
TextBoxUserName,
TextBoxPassword.
Let's say you have one record in your TblUsers like this
Id : 1
UserName : rammstein
Password : ohnedich
LoginAttempt : 0
Now, you are in your Login.aspx.cs code
you have a method and in it you have
TblUsers user = new TblUsers();
And you have a bool login = false;.
You've got the username from TextBoxUserName.Text, you check if a user with this username exists then if it exist you do the below code.
Let's follow this scenerio
The given user tried to login with
UserName:rammstein
Password:duhast
Checked your database with username rammstein and found it, and took that record in your TblpUsers user then you checked whether user.Password and TextBoxPassword.Text matches.Well it won't match for the above example because
user.Password is ohnedich however TextBox.Password is duhast.This means the login is not successfull so you set false to your bool login.
Everything else belongs to the below code with if-else condition
if(user.LoginAttempt < 3){
if(!login)
{
user.LoginAttempt = user.LoginAttempt + 1;
}
else
{
user.LoginAttempt = 0;
}
}
else
{
//do something
}
Multiple solutions:
1) Session variable (Okay solution)
2) Static class variable (Not a good solution)
3) DB record field (Best solution)
4) Pass flag variable back and forth between view and controller (not a very good idea).
5) Browser cookie (can be cleared)

Create our own login functionality in asp.net without using default logincontrol of ASP.NET

How to Create a Login, Signup and after user Login then loggedin username will be dispalyed in every page using Label with out using login control and create userwizard
I have following Field in My Table1
ID Username Email id Password
1 dobriyal dd#d.com ssssss
2 manish tt#d.com ttreter
i want to create login in sumit.aspx page using Textbox1 and textbox2 and button ...when user eneter emailid in textbox1 and password in textbox2 then if userfind in database according to the emailid and password entered in textbox1 and textbox2 .... then loggedin username will be displayed in label1 of each page ...where i have label 1 on page ///
means .... if i have label1 on Default.aspx, myname.aspx, defaul2.aspx then in each page the label1 text would be loggedin username .....till they loggedit its session ...
How to do it using Vb.NET
Remember I dont wanna use default login & createuserwizard, login status and login name control of ASp.NET ...
Answer of your question is very broad. So instead of code i am giving you the algorithm.
1. Create a method that will check the supplied user name and password in your data layer file.
E.g. bool IsAuthenticatedUser(). Inside this method run Command.ExecuteScalar. Here is query "
Declare #Count =(Select Count(*) From Login
Where UserName = #UserNAme and Password = #Password)
Select #Count;
-- Assuming u r using Sql Server 2008
2. Now in your IsAuthenticated Method check if the returned value is one then return true else false. Something like this
int count = (int)command.ExecuteScalar();
If (count ==1)
{
return true;
}
return false;
3. On the UI check the value returned by the method. If its true redirect the user to its page. And set session. For displaying name email id on page,
After the success of IsAuthenticated method, Create another method that will select your desired entities from database and fill it in datatable.
Something like this
If(IsAuthenticatedUser(username, password))
{
Datatable dt = GetUserDetails(username,password);
If(dt!=null)
{
if(dt.rows.count >0)
{
// here there is only one row so you can use index [0] also
foreach(DataRow dr in dt.rows)
{
Session["UserName"] = dr["UserName"].tostring();
Session["Email"] = dr["Email"].tostring();
}
}
}
Now on the desired page check if the both sessions are not null , then set the value at desired label.
If (Session["UserName"]!=null && Session["Email"]!=null)
{
lblUserName.Text = "Welcome " + Session["UserName"].ToString();
lblEmail.Text = Session["Email"].tostring();
}
**Here userName and password parameter will be the value passed from the textbox.
string username = txtUserName.text.trim();
string password = txtPassword.text.trim();
Also you to put validations before accepting input from users, as this may result in sql injection and exposing of your entire database. but for home purpose you can do this.**
See Update:
For displaying name on every page Create a master page and add the two labels on that. For adding master page , from context menu Add New Item -> MasterPage. Now in source view add table as per your need. Also there is ContentPlaceholder , do not add inside that tag. That is the space to display the other child pages. in the master page load event use the label = session code to set the name. Also there add a link button , in its click event use
Session.Abandon();
Response.Redirect("~/Login.aspx?Logout=1");
-> i have added a new thing ?Logout called query string , used for passing values from one page to another. Here i am using Login =1 that means I can know ia m on login page because i logged out myself.

How do I Keep a user logged in for 2 weeks?

HI
I am using asp.net mvc with asp.net membership.
I want to have a checkbox that if clicked keeps the users signed in for 2 weeks(unless they clear their cookies).
So I know their is
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie)
but I don't know how to set it up for 2week retention.
I rewrote most of the membership stuff. So I don't use stuff like Create() and VerifyUser().
Add a hash key or a random string to both the cookie and the database (both the same key). If the cookie and database value are the same, when the user starts a new session, sign him/her in again. When the user reaches the two weeks, remove the secret key from the database using a cronjob (Unix) or scheduled task (Windows).
Warning: Do not rely on the cookie expire date, since people can hack their browser.
Rule: NEVER, EVER trust ANY of your users!
You can set the global session timeout (the value is in minutes) in web.config eg.
<system.web>
<authentication mode="Forms">
<forms timeout="20160"/>
</authentication>
</system.web>
This will be for all authenticated users. If you want to use the 'Remember Me' functionality then you will need to write your own code to set the cookie/ticket. Something like this (taken from here):
protected void Page_Load()
{
if (Request.Cookies["username"] == null || Request.Cookies["username"].Value.ToString().Trim() == "")
{
Login1.RememberMeSet = true;
}
else
{
Login1.UserName = Request.Cookies["username"].Value.ToString().Trim();
Login1.RememberMeSet = true;
}
}
protected void RememberUserLogin()
{
// Check the remember option for login
if (Login1.RememberMeSet == true)
{
HttpCookie cookie = new HttpCookie("username");
cookie.Value = Login1.UserName.Trim();
cookie.Expires = DateTime.Now.AddHours(2);
HttpContext.Current.Response.AppendCookie(cookie);
Login1.RememberMeSet = true;
}
else if (Login1.RememberMeSet == false)
{
HttpContext.Current.Response.Cookies.Remove("username");
Response.Cookies["username"].Expires = DateTime.Now;
Login1.RememberMeSet = false;
}
}
Just use a simple cookie with 2 weeks expiration date.
Have you seen this?
http://forums.asp.net/t/1440824.aspx
Along similar lines to what Koning has suggested.
You can not use a session method to keep your users logged in, since browsers delete the session cookies when the browser is closed.
Do what user142019 offered and set the session's IdleTimeout parameter very short, up to 15 min. When the server receives any request from the browser, first check the session if it's alive. if not, try to get the cookie. If the cookie and database value are the same and not expired, assign it to the (new) session and return the response.
You can use onBeforeUnload listener to send a logout request when the user leaves your site. If logged out, delete the cookie and the db record, if not - assign a new hash for the next auto login and refresh that hash again when the user retunes to your website. You can also keep track of IP and the browser and link them to the hash in your db.
So, in case if the cookie is used with another browser or IP, and the hash code is valid, you can force them to login again.

Resources