Monitor/logging who signs into the asp.netapp? - asp.net

I want to have a log file keep rows of who logs in and timestamp. is there a place to do this? And what sort of code is needed?

The default MembershipProvider can let you know when was the last time that a given User logged in to your site.
Look at MembershipUser. It has the following properties that might be of use for you:
MembershipUser.LastActivityDate
MembershipUser.LastLoginDate
.
If you are using webforms you can suscribe to the Login.LoggedIn event of the Login Control. In your callback function you can then log the login to your persitant store (database table, xml file, ...).
If you are not using the login control you could also register a handler for the HttpApplication.AuthenticateRequest. This would also work for asp.net mvc.

On the Login module/page on your site add the OnLoggedIn the OnLoggingIn and the OnLoginError , and there log your users.
In this functions, you can get the user name by find the UserName control
TextBox txtUserName = (TextBox)Login1.FindControl("UserName");
or if the user have been logged in, by the sender infos
protected void OnLoggedIn(object sender, EventArgs e)
{
//-> ((Login)sender).UserName
}
Then log your users - the datetime of login is of cource the DateTine.Now

Related

How to implement login session in asp.net and C#

I'm new to asp.net and C# and I want to ask how to implement a session login using asp.net and C#.
Please advise.
Thanks.
In C# you can define a session variable like this:
Session["userame"]= txtusername.Text;
where txtusername is a text box. In another page you can call it as:
string usrname = Session["username"].ToString();
To check whether a user is logged in or not, in a particular page; you'll have to check if this session is empty or not. If the session is null then redirect the user to login page else he/she can view the page. Same logic applies to all the pages where you want to implement the session validation. Sample (on Page_Load event):
if (Session["username"] == null)
Response.Redirect ("Login.aspx");
Hope it helps... :)
The question is broad answer, in Simply you can follow like this
Create database, user table in sql server or any database of your choice
Create the login form with userid and password
Check them with database for user availability
If User exist and password matches create a session, like Session.Add ("Userid", txtUserid.Text);
In other pages (restricted pages where only registered users allowed) write this code in every page load event
if (Session["Userid"] == null)
Response.Redirect ("Login.aspx");
Session["login_user"] = "[username]";
string username = Session["login_user"].ToString().Trim();
Easiest way to implement session is as following:
Session["SessionName"] = Value;
For retrieving value
String variable = Session["SessionName"].ToString();
Note: Session variable can be of any type.
Generally session is used for checking whether the user is logged in or not.

Where should i store "MemberID"?

In my webpage i use FormsAuthentication
FormsAuthentication.RedirectFromLoginPage(VisitorEmail, False)
Every time the visitor gets authenticated via the login page, i set the
Session("MemberID") = GetMemberIDByEmail(VisitorEmail) for later processing.
Since i need both MemberID and VisitorEmail.
But something tells me that this is "out of the book" and not "by the book".
So am i doing something WRONG or BAD here?
Sorry, I'm not sure exactly what you are trying to do from your description, but there's no need to store the MemberID in session state. Whenever you need it, just call:
Membership.GetUser.ProviderUserKey
Note: Its not really considered good form to store information in Session state as this could be lost e.g. if the web server resets - which it does periodically, or if the site needs to recompile. Also, its not very scalable as each "active" user will use up memory and also if you ever need to move to a web farm session state can cause issues as it will be different on each web server.
Prob OK for a little, quick site though ;-)
It's fine to use Session to cache this type of info, but remember to reassign it when the session expires in Global.asax:
void Session_Start(object sender, EventArgs e)
{
if(Request.IsAuthenticated) //to make sure the user has not logged out
Session["MemberID"] = GetMemberIDByEmail(VisitorEmail);
}
You could create a custom principal class so you can add the additional properties. Then modify your Global.asax to override Application_PostAuthenticateRequest with your code and also set Context.User = Thread.CurrentPrincipal = myPrincipal;. Best is to always set Thread.CurrentPrincipal, but normally you can also get to your own properties elsewhere in your code using the more "convenient" Page.User or Context.User.
Context.User vs. Thread.CurrentPrincipal / why FormsAuthentication can be subtle
Set custom IIdentity or IPrincipal / Store user id in Principal or Identity?
Could you not switch the two around and store the member id in the form variable (since I assume the user is able to change there email address and not there member id)...
Dim memberId as Integer = GetMemberIDByEmail(VisitorEmail)
' assuming integer here and that a result is found etc etc
' set the form authentication stuff
FormsAuthentication.RedirectFromLoginPage(memberId, False)
And then you can always look up the email address from the memberId (caching it perhaps against the member id across requests)
Public Function GetMemberEmail(Byval memberId as Integer) As String
Dim cacheKey as String = "member-email-" & memberId
Dim email as String
If Cache.Item(cacheKey) is Nothing Then
email = GetMemberEmailByID(memberId)
Cache.Insert(cacheKey, email ...
Else
email = Cache.Item(cacheKey)
End If
return email
End Function
If you need both pieces of information, and the Id is less likely to change, it would seem the better value to be used for your forms authentication....and you can always look up the email address from the value.

Save username in session variable when users logins using Http Module

Is it possible to use an application event to save the username in a session variable? I would like to do something like this:
private void ContextOnBeginRequest(object sender, EventArgs eventArgs){
if (_context.Request.IsAuthenticated)
_context.Session["ID"] = _context.User.Identity.Name;
}
However in the above code I get an error saying that Session state is not available.
If you want to take this approach you should check httpcontext.current.session, but of course first make sure it's not null. In addition, you'll want to check to see that the Request IsAuthenticated as well to ensure there is a user because you can have a session that isn't authenticated.
ContextOnBeginRequest is your BeginRequest event handler. If this event
fires the SessionState is not createt yet.
s. HttpApplication Class -> Remarks

ASP.NET Membership - keep users to use previous passwords

I created a Membership login system for my client, now they do NOT want the user to use one of his 5 last passwords when it comes time to create a new one.
Is that something that is build in or how could I accomplish that?
This feature doesn't exist on asp.net membership login system.
You must implement it by yourself, on the automatic-creating page of changing password.
You need somewhere to save the previous hash list of your users passwords, and check this list, just before accepting a password change.
Update
Where to start:
Start from the all ready existing password change control.
Here is a password change example.
http://www.asp.net/cssadapters/Membership/ChangePassword.aspx
In this control, (that you can easy drag and drop on your page) capture the events,
<asp:ChangePassword ID="ChangePassword1" runat="server"
onchangingpassword="ChangePassword1_ChangingPassword" ... >...
Make your function to check for old passwords
protected void ChangePassword1_ChangingPassword(object sender, LoginCancelEventArgs e)
{
if (PasswordFoundOnList())
{
... show an error....
e.Cancel = true;
}
}
Now save somewhere the last passwords, for example you can saved them on user profile, or on your database.
here are some more informations for user profile.
http://www.asp.net/Learn/Ajax/tutorial-03-cs.aspx
Hope this help you make it.
Check this awesome post by Ronan Moriarty:
Implementing Password History using a Custom Membership Provider
It's an extensive post and I used option 2 as he describes. It has helped me implement what you ask. It's working great here.

How do I use a ASP.NET Login control without using a MembershipProvider?

This is an offshoot of this question.
How do I use a Login control if I don't have a MembershipProvider to point it at?
Am I understanding the use model correctly?
Is it even reasonable to talk about using a Login control without a MembershipProvider?
Dose the MembershipProvider do more than just username/password checking?
Would it be more reasonable to create my own MembershipProvider with the same authentication logic?
In my case, I don't need a MembershipProvider (I think) as my authentication situation is trivial (one user, one password).
I'm interested partly to "future proof" my page and partly because I'm new and wondering about how stuff works. (I tend to learn about things by running full speed into every corner case I can find :)
You can just drop the asp:Login control in your page, then in the code behind, catch the Login Control's Authenticate event.
In the Authenticate event, check the username/password that the user has entered. The username/password are properties in the login control. (LoginCtrl.UserName, LoginCtrl.Password)
If the username/password is correct, just set the event args Authenticated property to True.
No membership provider is required.
ex. In the aspx page..
<asp:Login ID="LoginCtrl" runat="server" DestinationPageUrl="YouAreIn.aspx"></asp:Login>
In Code Behind
Private Sub Log_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles LoginCtrl.Authenticate
If LoginCtrl.UserName = "Hello" AndAlso LoginCtrl.Password = "Hello" Then
e.Authenticated = True
End If
c#
void MyLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
if(UserName == "Hello" && Password == "Hello")
e.Authenticated = true;
}
If you don't have a membership provider and don't really have a security system to speak of, just put two boxes on a form (user name, password) and test it in the onclick of the button.
The login control is obviously overkill for what your trying to do.
Use Simple Forms Authentication.
You would have to make a custom authentication provider and plug it in via web.config. http://www.devx.com/asp/Article/29256

Resources