Membership provider class - c#

I want to know how I can implement membership provider class to have ability to remember users who signed in.
I have Membership provider class and I need functionality of "Remember Me" checkbox but I don't know how I can implement some methods

In order to implement this functionality you must create a persistent cookie with some expiration date on the users computer. So if the user checks the Remember me checkbox you issue the following cookie:
var cookie = new HttpCookie("_some_cookie_name_", "username")
{
Expires = DateTime.Now.AddDays(15) // Remember user for 15 days
};
Response.Cookies.Add(cookie);
And then upon showing the login screen you could check if the cookie is present and prefill the username:
var cookie = Request.Cookies["_some_cookie_name_"];
if (cookie != null)
{
usernameTextBox.Text = cookie.Value;
}

I would use a Hashtable if it's in C#, keyed by the user id. Something like this (where lsdfjk is just whatever string the user ID corresponds to, and assuming that there is a class UserInfo defined, with a constructor taking string userID as an argument):
string userID = "lsdfjk";
UserInfo userInfo = null;
Hashtable htMembers = new Hashtable();
if (htMembers.ContainsKey(userID))
{
userInfo = (UserInfo)htMembers[userID];
}
else
{
//It's a new member
userInfo = new UserInfo(userID);
}

"Remember Me" doesn't have anything to do with a Membership Provider really. Basically it is just a function of Forms Authentication, where you set a persistent cookie so that when people show up at the website, it can log them in automatically.
You can do this automatically using the RedirectFromLoginPage() method.
FormsAuthentication.RedirectFromLoginPage(username, true);
The second parameter, "true", means "set a persistent cookie". The user will be logged in until the cookie expires or they clear their cookies.
If you need more control over it, you can manually set a cookie by manipulating the cookies collection directly.

Related

How to get logged in users data (in a secure way)

I'm using ASP.NET MVC Entity Framework.
In my application I'm currently able to login and retrieve some data, but I'm not sure if the way I do it is a secure way.
Here is how my application works:
Currently when a user logs in, I make use of the following to store the username in a cookie:
FormsAuthentication.SetAuthCookie(user.Username, true);
Then I have a RoleProvider class that contains the following method, which returns a string array with the users role:
public override string[] GetRolesForUser(string username)
{
List<string> rolesList = new List<string>();
string role = CurrentlyLoggedInUser.User.Role.Name;
rolesList.Add(role);
string[] rolesArray = rolesList.ToArray();
return rolesArray;
}
Then I have the following class, that stores data of the currently logged in user:
public class CurrentlyLoggedInUser
{
private const string UserKey = "MyWebApp.Infrastructure.UserKey";
public static User User
{
get
{
MyDBEntities db = new MyDBEntities();
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
return null;
}
var user = HttpContext.Current.Items[UserKey] as User; //we set the
if (user == null)
{
user = db.Users.FirstOrDefault(x => x.Username == HttpContext.Current.User.Identity.Name);
if (user == null)
{
return null;
}
HttpContext.Current.Items[UserKey] = user;
}
return user; //Then we return the user object
}
}
}
Then whenever I need to query the database to find any related data of the user, I retrieve the users Id as follow:
int id = CurrentlyLoggedInUser.User.UserId;
Now I can make queries using this Id.
When I'm done, I logout and call the following:
FormsAuthentication.SignOut();
Is this recommended and secure enough?
Consider requiring https to secure you login form, don't forget about Authorize attribute on your MVC controllers and/or actions (or, preferably set Authorize attribute as a global filter) and on the basic level that's enough. #Chad-Nedzlek is not absolutely correct, FormsAuthentication, you involve, takes care about your authentication cookie encryption, so it's not so easy for anyone to impersonate any other. But you have to take care about preventing bruteforce attacks when implementing your custom login: consider password lifetime limitation, required complexity etc.
And if you are thinking about future extensibility, SSO for web, mobile apps and API, or possibility of easy use of external (Facebook, Google etc) login, consider switching to OpenId Connect.

Header Manipulation Cookies in asp.net

Fortify tool is showing the Header manipulation cookies issue on the below code.
HttpCookie cookieexit= new HttpCookie("CheckUserNameExists");
cookieexit.Value = userName;
cookieexit.Secure = true;
Response.Cookies.Add(cookieexit);
Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, false));
Any help ?
It is not directly related to original question.
If you use FormAuthentication, it is not a good practice to create custom cookie name to keep track of logged-in username.
Instead, you want to use same cookie name FormsAuthentication.FormsCookieName that FormsAuthentication uses.
So, you replace 5 lines of codes with the following single line -
FormsAuthentication.RedirectFromLoginPage(userName, false);
Global.asax.cs
You then retrieve the username from cookie, and save it in both Principal Object and Current Thread.
public class Global : HttpApplication
{
private void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie decryptedCookie =
Context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(decryptedCookie.Value);
var identity = new GenericIdentity(ticket.Name);
var principal = new GenericPrincipal(identity, null);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = HttpContext.Current.User;
}
}
You can then retrieve username literally anywhere in your code as long as HttpContext.Current is available. For example,
string userName = User.Identity.Name;
Fortify is complaining because it thinks that userName could have dangerous characters, such as newlines, which could (maybe) allow header manipulation attacks in the scenario of social engineering/phishing attacks.
I'm not too sure of the practicality of such attacks, but I am pretty sure that if you validate that userName only contains a whitelisted set of characters that exclude any whitespace, then such an attack is prevented.

Custom MVC Authentication without SetAuthCookie()

Because of the requirements of my project, I'm wanting to provide custom authenticate for my MVC controller actions. Therefore, I will not be using SetAuthCookie().
Intially I set a cookie as follows;
string userData = EncDec.MakeString(user.Email + "|" + user.UserId);
//the Cookie and FormsAuthenticationTicket expiration date/time is the same
DateTime cookieExpiry = DateTime.Now.AddMinutes(AccountPage.MvcApplication.COOKIE_EXPIRY_MINUTES);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
user.UserName, // authenticated username
DateTime.Now, // issueDate
cookieExpiry, // expiryDate
false, // true to persist across browser sessions
userData, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
//create the cookie
HttpCookie cookie = new HttpCookie("ADV_" + Extensions.ControllerExtensionMethods.GetGuid(this), encryptedTicket);
cookie.Secure = true;
cookie.HttpOnly = true;
cookie.Expires = cookieExpiry;
Response.Cookies.Add(cookie);
The HttpCookie is being saved in the client browser with a encrypted FormsAuthenticationTicket.
Then within my controller actions, whenever I need to check and verify that the user is authenticated I call this method;
public static FormsAuthenticationTicket IsAuthenticated(string guid)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["ADV_" + guid];
if (cookie != null)
{
string encryptedTicket = cookie.Value;
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encryptedTicket);
if (!ticket.Expired)
{
//if the user is authenticated and the cookie hasn't expired we increase the expiry of the cookie - keep alive
DateTime cookieExpiry = DateTime.Now.AddMinutes(AccountPage.MvcApplication.COOKIE_EXPIRY_MINUTES);
//create a new ticket based on the existing one
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
ticket.Version, // ticket version
ticket.Name, // authenticated username
ticket.IssueDate, // issueDate
cookieExpiry, // expiryDate, changed to keep alive if user is navigating around site
false, // true to persist across browser sessions
ticket.UserData, // can be used to store additional user data
ticket.CookiePath); // the path for the cookie
string newEncryptedTicket = FormsAuthentication.Encrypt(newTicket);
//keep alive
HttpCookie newCookie = new HttpCookie("ADV_" + guid, newEncryptedTicket);
newCookie.Secure = true;
newCookie.HttpOnly = true;
newCookie.Expires = cookieExpiry;
HttpContext.Current.Response.Cookies.Set(newCookie);
return newTicket;
}
}
return null;
}
Every time the user is re-authenticated, I am increasing the time out of when the cookie will expire, so that the login is keep alive.
Everything seems to work fine, and the users are correctly authenticated, and if they aren't authenticated I redirect them to a login page, and they can't access methods if they aren't authenticated either.
My questions are:
Is this way of dealing with the authentication secure.
Is there anything I should be aware of, in terms of a security risk.
Thanks.
You basically need to look at creating a Custom Authentication Attribute.
I'm not going to provide the actual implementation here, but this will put you on the right path.
Here's the basic representation :-
public class GoogleAuthAttribute : FilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
IIdentity ident = filterContext.Principal.Identity;
if (!ident.IsAuthenticated || !ident.Name.EndsWith("#google.com"))
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result =
new RedirectToRouteResult(new RouteValueDictionary
{
{"controller", "GoogleAccount"},
{"action", "Login"},
{"returnUrl", filterContext.HttpContext.Request.RawUrl}
});
}
}
}
I've took this from the Apress Book i'm currently reading on MVC5. If OnAuthentification fails, you set the Result property of the AuthenticationContext, this is then passed to the AuthenticationChallengeContext, where you can add your challenge code.
In my example, the user is redirected to the login page.
All you need t do, is place this AuthentificationAttribute on the Action Methods you require.
You should be able to build in or work your custome security code in to this.
You should really ask yourself if its a good idea to be adding custom security measures, as it can lead to more problems that you want.

Is it possible to update the current IPrincipal without creating a new connection in SignalR 2.0.x?

We use custom forms authentication in MVC4. We create a FormsAuthenticationTicket with custom data (another authentication ticket for a backend sub system) and store it in a cookie. This cookie is read and dectypted in the FormsAuthentication_OnAuthenticate method in global.asax. From the decrypted data we create a custom IPrincipal object that we set as the current User.
We also use a sliding expiration scheme for the ticket and if it's about to expire we create a new ticket and update the cookie and create a new custom IPricipal object.
We have set ut SignalR to ping the server regularly, and the ticket is correctly renenewd.
The problem is that the updated IPrincipal is never propagated to SignalR (it's only set the first time). Is this even possible or do we need to create a new connection when the ticket is renewed?
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
{
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
return;
var ticketManager = DependencyResolver.GetService(typeof(ITicketManager)) as ITicketManager;
var ticket = ticketManager.DecryptAndValidateTicket(authCookie.Value);
var newTicket = ticketManager.RefreshTicketIfNeeded(ticket);
if (newTicket != null) {
var cookie = ticketManager.CreateCookie(newTicket);
e.Context.Response.Cookies.Add(cookie);
ticket = newTicket;
}
var user = ticketManager.Authenticate(ticket);
Thread.CurrentPrincipal = user;
HttpContext.Current.User = user;
e.User = user;
}
You need to create a new connection if you want to update the current IPrincipal of a SignalR connection.
The reason is pretty straightforward: SignalR requests can last indefinitely.
Cookies are sent and authentication/authorization occurs at the beginning of a request. This is also when the IPrincipal is set. In SignalR at least, the IPrincipal is stored on the request itself.
I suppose it might be possible to update the IPrincipal if you had references to the active SignalR requests for the given user, but I think your best bet is establishing a new SignalR connection if the IPrincipal changes.

How to get recently authenticated user?

I am working with MVC 3 and I have just implemented a wrapper for the FormsAuthenticationService.
Something similar to the following.
public void SignIn(string username, bool createPersistantCookie)
{
if (string.IsNullOrEmpty(username))
throw new ArgumentException("Value Cannot be null or empty", "username");
FormsAuthentication.SetAuthCookie(username, createPersistantCookie);
}
Reluctantly, I have gotten this to work, but now I am not quite sure how to get the information that I have stored.
Once the user is in my system, how can I now safely retrieve this information if I need to grab their UserID out of the database?
Based on the additional information provided, you want to store additional data with the FormsAuthentication ticket. To do so, you need first create a custom FormsAuthentication ticket:
Storing Data
Grab the current HttpContext (not worrying about testability)
var httpContext = HttpContext.Current;
Determine when the ticket should expire:
var expires = isPersistent
? DateTime.Now.Add(FormsAuthentication.Timeout)
: NoPersistenceExpiryDate; // NoPersistenceExpiryDate = DateTime.MinValue
Create a new FormsAuthentication ticket to hold your custom data.
var authenticationTicket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.Add(FormsAuthentication.Timeout),
isPersistent,
"My Custom Data String"); //Limit to about 1200 bytes max
Create your HTTP cookie
new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authenticationTicket))
{
Path = FormsAuthentication.FormsCookiePath,
Domain = FormsAuthentication.CookieDomain,
Secure = FormsAuthentication.RequireSSL,
Expires = expires,
HttpOnly = true
};
And finally add to the response
httpContext.Response.Cookies.Add(cookie);
Retrieving Data
Then you can retrieve your data on subsequent requests by parsing the stored authentication ticket...
Again, grab current HttpContext
var httpContext = HttpContext.Current
Check to see if the request has been authenticated (call in Application_AuthenticateRequest or OnAuthorize)
if (!httpContext.Request.IsAuthenticated)
return false;
Check to see if you have a FormsAuthentication ticket available and that it has not expired:
var formsCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (formsCookie == null)
return false;
Retrieve the FormsAuthentication ticket:
var authenticationTicket = FormsAuthentication.Decrypt(formsCookie.Value);
if (authenticationTicket.Expired)
return false;
And finally retrieve your data:
var data = authenticationTicket.UserData;
You haven't actually stored a user id in the database. All the code that you've written does is store an authentication cookie on the users computer, either as a session cookie (not persistent) or as a persistent one.
When your page refreshes, it will get the cookie automatically, decode it, and populate the IPrincipal object which you access from the User.Current property of your controller.

Categories