Wednesday, 15 September 2010

security - Using cookies to auto-login a user in asp.net (custom login) -



security - Using cookies to auto-login a user in asp.net (custom login) -

i can't find on net i'm looking help appreciated. have implemented custom login form user enters email , password log in. query database credentials (password hashed , salted) , if both found store userid in session state. if user closes browser session lost have log in again. learned using cookies implement "remember me" functionality don't know should storing in cookie auto-login process , create secure.

ps: know cookie , how works. know storing user credentials (email + password) in cookie not advised. i'm using asp.net 4.0 c#

actually i'm looking logic behind auto-login scheme using cookies.

thanks!

you should utilize formsauthentication set cookie:

formsauthentication.setauthcookie(theuserid, true);

and back:

string userid = httpcontext.current.user.identity.name;

if worried security, can consider using secure cookies (you able read cookie on https).

there's more info on in related post: manual access command in asp .net

update: according comment, don't think can set forms authentication cookie in custom login form. created blank asp.net 4 project, created custom login -- log in unauthenticated user. here 3 pieces:

the web.config (your project should have similar since have form on site people login):

<authentication mode="forms"></authentication>

the code front:

<%@ page language="c#" autoeventwireup="true" codebehind="default.aspx.cs" inherits="emptywebapp._default" %> <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>example</title> </head> <body> <form id="form1" runat="server"> <div> username: <asp:label id="_username" runat="server"></asp:label> </div> </form> </body> </html>

the code behind:

using system; using system.web; using system.web.security; namespace emptywebapp { public partial class _default : system.web.ui.page { protected void page_load(object sender, eventargs e) { if (httpcontext.current.user.identity.isauthenticated) { _username.text = httpcontext.current.user.identity.name; } else { _username.text = "not logged in"; formsauthentication.setauthcookie("cookieman", true); } } } }

as can see, can set authentication cookie using formsauthentication.setauthcookie in own custom authentication function, 1 irrational this.

in case, first time nail page, show username: not logged in , log them in "cookieman". refreshing page show username: cookieman.

asp.net security cookies login persistent

No comments:

Post a Comment