I have a simple login form on my mvc application and it works correctly except for when you try to login with a user that isn't in the database.
It will throw an error Sequence contains no elements which makes sense since theres no matching users in the database although I try to handle it in the code it is not doing it.
// POST: Login User
[HttpPost]
public ActionResult Login(UserAccount user)
{
using (MyDbContext db = new MyDbContext())
{
var usr = db.Users.Single(u => u.UserName == user.UserName && u.UserPassword == UserPassword);
if (usr != null)
{
Session["UserID"] = usr.UserId.ToString();
Session["Username"] = usr.UserName.ToString();
return RedirectToAction("LoggedIn");
}
else
{
ModelState.AddModelError("", "Username or Password Incorrect");
}
}
return View();
}
Single will throw an exception if no match is found, or too many are found. Using SingleOrDefault like so returns null in the case where no match is found:
var usr = db.Users.SingleOrDefault(...)
This sets you up for the null check you're doing right afterwards.
So...As some people said in the comments above, you could just simply use the following query and then do your null check:
var usr = db.Users.SingleOrDefault(u => u.UserName == user.UserName && u.UserPassword == UserPassword);
That being said, I would recommend looking into using the built in ASP Identity framework for authentication and authorization - unless you need a custom implementation for your application, you can avoid a lot of testing (and potential bugs) as well as get a ton of cool out-of-the-box features. I would recommend checking out the resources here for more information.
Related
I am making a login page and i saved the user's details and hashed password in the CUSTOMERS table, but i cant send the salt and the typed password i get from the database and the user to my method
var UserInput = db.CUSTOMERs.Where(b => b.EMAIL == cUSTOMER.EMAIL && b.PASSWORD == sha256(b.SALT+cUSTOMER.PASSWORD).ToString()).FirstOrDefault() ;
Hash method
static string sha256(string password)
{
System.Security.Cryptography.SHA256Managed crypt = new System.Security.Cryptography.SHA256Managed();
System.Text.StringBuilder hash = new System.Text.StringBuilder();
byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(password), 0, Encoding.UTF8.GetByteCount(password));
foreach (byte theByte in crypto)
{
hash.Append(theByte.ToString("x2"));
}
return hash.ToString();
}
You have the error because Linq To Entities hence Entity Framework can't be used to compose with function that can't be translated into SQL. So your custom method sha256 and ToString.Net method are the main causes.
To make it work you must first get the user by email then check that the user has his password hash equal to the genrated one.
So you need to rewrite your code like this:
var UserInput = db.CUSTOMERs.FirstOrDefault(b => b.EMAIL == cUSTOMER.EMAIL);
if(UserInput != null && UserInput.PASSWORD == sha256(UserInput.SALT+cUSTOMER.PASSWORD))
{
// The user email and password match
}
else
{
// The user not found or the password does not match
}
We override the basic authentication in an MVC3 application by calling a webservice with the user's credentials and returning a WCF structure that contains the user's ID, a "LogonTicket". This LogonTicket is used to "authenticate the user for each call made to the webservice.
Now, we override by replacing the defaultProvider in the Web.config. All we do in this overridden provider is
to override the ValidateUser() function. That is where we call the web service with their credentials and return
the "LogonTicket".
This is the LogOn() function from our AccountController, essentially the base code from the template:
public ActionResult LogOn(LogOnModel model)
{
string ReturnUrl = "";
if (HttpContext.Request.UrlReferrer.Query.Length > 11)
{
ReturnUrl = Uri.UnescapeDataString(HttpContext.Request.UrlReferrer.Query.Substring(11));
}
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(ReturnUrl) && ReturnUrl.Length > 1 && ReturnUrl.StartsWith("/")
&& !ReturnUrl.StartsWith("//") && !ReturnUrl.StartsWith("/\\"))
{
return Redirect(ReturnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
ViewBag.MainWebsite = MainWebsite;
return View(model);
}
This is the overridden ValidateUser() function from our new default provider:
public override bool ValidateUser(string username, string password)
{
MyServiceClient mps = new MyServiceClient();
string sha1password = HashCode(password);
LogonInfo logonInfo = mps.GetLogonTicket(username, sha1password);
if (logonInfo.LogonTicket != "" && logonInfo.LogonTicket != "0")
{
// Authenticated so set session variables
HttpContext.Current.Session["LogonTicket"] = logonInfo.LogonTicket;
HttpContext.Current.Session["ParticipantID"] = logonInfo.ParticipantID;
return true;
}
else
{
return false;
}
}
I'm not really sure how to combine the use of the two, so my questions are:
How can I implement OpenID and Facebook logins and keep my current authentication method?
How can we "map" the OpenID user with our current user DB values? We MUST know so we can retrieve their info.
I know we can retrieve their email address but what if their OpenID email is different than the one they use for their record on our site?
Are there any examples of how to do this, anywhere?
Thanks for looking at my question.
I have done a project which required multiple log-on possibilities (custom account, Google and Facebook)
In the end your authentication with ASP.NET is entirely dependant on your configuration. (In your case it is FormsAuthentication) this means that FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); basicly determines everything in regard to your user and where you set this isn't restricted.
You have now basicly the same implementation as we started out with, using a MembershipProvider to handle your own custom account. You only need to expand now to facilitate the openIds. You would have to expand your Controller with various actions for each login type (Now you have ActionResult LogOn() you can add to that for example: ActionResult LogOnOpenId()). Inside that method you basicly call the same code but instead of Membership.ValidateUser(model.UserName, model.Password) you call the OpenId services.
I have provided below an example of our google implementation using dotnetopenauth. The service method uses formsService.SignIn(userId.Value.ToString(), false); which basicly calls FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); (we only do some custom behaviour there in regard to the SecurityPrincipal but this doesn't affect your Authentication process). You can also see that we make a new account when we receive a new user. To solve your question part 2 we have implemented a profile which can be merged if you can provide another login. This allows our users to keep their account consolidated and use whatever login method they like.
For examples in regard to multiple signons I will refer to the answer of Tomas whom referenced StackExchange as a good example. Also I'd advise you to install MVC4 and VS2012 and just do a File > New Project. The newest default template of MVC includes openid implementation alongside a custom login!
Example google openid implementation:
The controller method:
public virtual ActionResult LoginGoogle(string returnUrl, string runAction)
{
using (var openId = new OpenIdRelyingParty())
{
IAuthenticationResponse response = openId.GetResponse();
// If we have no response, start
if (response == null)
{
// Create a request and redirect the user
IAuthenticationRequest req = openId.CreateRequest(WellKnownProviders.Google);
var fetch = new FetchRequest();
fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
fetch.Attributes.AddRequired(WellKnownAttributes.Preferences.Language);
req.AddExtension(fetch);
req.RedirectToProvider();
return null;
}
_service.ConnectViaGoogle(response, TempData);
}
The service method:
public void ConnectViaGoogle(IAuthenticationResponse response, TempDataDictionary tempData)
{
// We got a response - check it's valid and that it's me
if (response.Status == AuthenticationStatus.Authenticated)
{
var claim = response.GetExtension<FetchResponse>();
Identifier googleUserId = response.ClaimedIdentifier;
string email = string.Empty;
string firstName = string.Empty;
string lastName = string.Empty;
string language = string.Empty;
if (claim != null)
{
email = claim.GetAttributeValue(WellKnownAttributes.Contact.Email);
firstName = claim.GetAttributeValue(WellKnownAttributes.Name.First);
lastName = claim.GetAttributeValue(WellKnownAttributes.Name.Last);
language = claim.GetAttributeValue(WellKnownAttributes.Preferences.Language);
}
//Search User with google UserId
int? userId = _userBL.GetUserIdByGoogleSingleSignOnId(googleUserId);
//if not exists -> Create
if (!userId.HasValue)
{
_userBL.CreateGoogleUser(
googleUserId,
firstName,
lastName,
email,
language,
DBConstants.UserStatus.DefaultStatusId,
out userId);
}
if (userId.HasValue)
{
_userBL.UpdateLastLogon(userId.Value);
var formsService = new FormsAuthenticationService();
formsService.SignIn(userId.Value.ToString(), false);
AfterLoginActions(tempData);
}
}
}
Any questions or comments? I'll gladly hear them.
it should be perfectly possible to have multiple authentications methods. All IIS / ASP.net cares about is the FormsAuthentication cookies. So you would have one set of actions for your standard username/password auth, and another for OpenId. This is at least what I have done on one project.
You can't even trust the openId provider to give you an email address! A common solution to this problem is to allow a user to attach multiple OpenId identifiers (URI's) to the his account after logging in. This is e.g. how StackOverflow works. If this is the first time the user visits the system then you can auto create a new account, or force the user through a signup process.
When I added the OpenId support in the system mentioned, it had an existing table used to store username and password(users table). I added a new table with a many to one relationship with the users table, and used this to store the URI's.
As mentioned above StackOverflow it self is a good place to start, also there are a lot of good examples in the http://www.dotnetopenauth.net/ project.
As far as I know the source of SO is not public, and they are using the dotnetopenauth project.
This may be to abstract, but this library is a openId (among other things) for the open source orchard CMS: http://orchardopenauth.codeplex.com/
I hope this helps, but if you have any questions then please expand your question with more details.
I currently working on an extension of the filter [Authorize], so that I can retrieve the permissions from the database. Everything works, but it is sure a performance issue. Every time I send a query to the database, asking for permission, and that is not the best way to determine this. So I thought to put these data in the Session. What is the fastest way to put a data from database in to Session object which I could ask (LINQ) as well as databases.
Now this looks like:
var _allowedRolesDB = context.sec_RolesInCAs
.Where(rl => rl.MenuControlName == controllRights && rl.MenuActionName == actionRights)
.Select(rl => rl.RoleName);
foreach (var r in _allowedRolesDB)
{
RolesDB = RolesDB + r.ToString() + ",";
}
but I want change to
var _allowedRolesDB = MySuperSessionSomethink
.Where(rl => rl.MenuControlName == controllRights && rl.MenuActionName == actionRights)
.Select(rl => rl.RoleName);
foreach (var r in _allowedRolesDB)
{
RolesDB = RolesDB + r.ToString() + ",";
}
where MySuperSessionSomethink will keep one-time-retrieved data from database. Any idea how I can do this? Tx for help.
BIGGER PICTURE
Ok. I will show bigger picture.
Whole idea is to create custom authorize filter.
[CustomAuthAttribute("Home,Index", Roles = "SuperAdministrator")]
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
What is a goal of this. Create authorize attribute which has all benefits, plus additional features like keep information about rights in database.
Now what I do is:
public CustomAuthAttribute(params string[] controllerAction)
{
IPrincipal user = HttpContext.Current.User;
string userName = user.Identity.Name;
**... some code .. and take all allowed roles and check it have permissions**
var _allowedRolesDB = context.sec_RolesInCAs
.Where(rl => rl.MenuControlName == controllRights && rl.MenuActionName == actionRights)
.Select(rl => rl.RoleName);
foreach (var r in _allowedRolesDB)
{
RolesDB = RolesDB + r.ToString() + ",";
}
**... some code .. thesame withs single users**
}
After this i use
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
**... can acces or not part of code ...**
if (_rolesSplit.Any(user.IsInRole))
{
return true;
}
}
But there is the problem. Everytime I ask database about permissions, and this IMHO is not best way. Now my idea is take all permissions for one user and put him into his session when hi is authorized. Maybe I'm wrong and this way will make problems, but keep in database and ask all the time about permissions is not good idea too :). So maybe better way to take data and use in code after only one or two questions to the database?
First of all, it seems like you would want to add these to the cache, and not the session. They seem global to the application, not specific to the user. Since you're doing a lookup of roles by menu control/action, I would just add them to the cache as a lookup:
string action = controlRights + actionRights;
string allowedRoles = Cache[action];
if (allowedRoles == null)
{
allowedRoles = String.Join(",", context.sec_RolesInCAs
.Where(rl => rl.MenuControlName == controlRights && rl.MenuActionName == actionRights)
.Select(rl => rl.RoleName)
.ToArray());
Cache[action] = allowedRoles;
}
This will give you the allowed roles for the given control/action, from the cache on the second request.
I have an MVC3 application and I would like to give the users the ability to set preferences that would be enabled when the user logs in.
I really don't have any idea where to start with this and would really appreciate being pointed in the right direction. I did try some changes to the membership class but now I am thinking that's probably not the best way to go about things.
You could do it in a database (sounds like you might be using one at least with the out-of-the-box membership provider) once uniquely identifying a user. In that case, you may want to implement your own membership provider.
You have to do a little work to start implementing your own provider. If this is your only requirement, you might be able to avoid it by writing your own class that returns settings in a format of your choosing
public static class UserSettings
{
public static string GetSettings(IPrincipal user)
{
if(user.Identity.IsAuthenticated)
{
// dip into database using user.Identity.Name property
return "string with user settings";
// this also assumes user.Identity.Name is uniquely able
// to identify a user in your database!
}
return string.Empty;
}
}
Or, if the information is completely trivial, maybe you could implement a cookie representation of the user settings. This, of course, comes with all the caveats of using cookies, but you could avoid storing the information in a database
Anywhere you have an HttpContext you could grab the settings value like so:
if(HttpContext.Current != null)
{
string userSettings = HttpRequest.Current.Request.Cookies["NameOfCookie"];
}
You can use the FormsAuthentication cookie to store your user information and avoid accessing the database all the time. That cookie is encrypted and whatever information you're storing as safe as the user session itself. The only problem with the cookies is that they have a maximum size of 4K so, if your user info is massive then you might run into a problem. When I use the cookie approach I store my user data as a JSON and then deserialize that JSON on each page request. Here is my login controller logic (I'm using SimpleMembership but the approach is the same:
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, model.RememberMe))
{
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null)
{
var user = _userLogic.GetItem(model.UserName);
if (user != null && user.IsActive)
{
var newAuthTicket = new FormsAuthenticationTicket(authTicket.Version, authTicket.Name, authTicket.IssueDate, authTicket.Expiration, authTicket.IsPersistent, JsonConvert.SerializeObject(user));
var newCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(newAuthTicket))
{
Expires = authCookie.Expires
};
Response.Cookies.Add(newCookie);
return RedirectToLocal(returnUrl);
}
WebSecurity.Logout();
ModelState.AddModelError("UserName", "This account has been deactivated.");
return View(model);
}
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
Notice the newAuthTicket creation and how user instance is passed to it as a JSON. After that all I have to do is desirialize this user object in my base controller's OnAuthorization method:
protected override void OnAuthorization(AuthorizationContext filterContext)
{
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null)
{
var principal = new CustomPrincipal(HttpContext.User.Identity)
{
CurrentUserInfo = JsonConvert.DeserializeObject<User>(authTicket.UserData)
};
HttpContext.User = principal;
AppUser = principal.CurrentUserInfo;
ViewBag.AppUser = AppUser;
}
}
base.OnAuthorization(filterContext);
}
Create a new table in your database.
I am using the following code from MVC Storefront to test OpenId in MVC. How do I integrate it with my ASP.Net Membership so I can use roles and save a user name for the user in my tables? I believe that SO is also using something similar.
public ActionResult OpenIdLogin()
{
string returnUrl = VirtualPathUtility.ToAbsolute("~/");
var openid = new OpenIdRelyingParty();
var response = openid.GetResponse();
if (response == null)
{
// Stage 2: user submitting Identifier
Identifier id;
if (Identifier.TryParse(Request["openid_identifier"], out id))
{
try
{
IAuthenticationRequest req = openid.CreateRequest(Request["openid_identifier"]);
var fetch = new FetchRequest();
//ask for more info - the email address
var item = new AttributeRequest(WellKnownAttributes.Contact.Email);
item.IsRequired = true;
fetch.Attributes.Add(item);
req.AddExtension(fetch);
return req.RedirectingResponse.AsActionResult();
}
catch (ProtocolException ex)
{
ViewData["Message"] = ex.Message;
return View("Logon");
}
}
else
{
ViewData["Message"] = "Invalid identifier";
return View("Logon");
}
}
else
{
// Stage 3: OpenID Provider sending assertion response
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
var fetch = response.GetExtension<FetchResponse>();
string name = response.FriendlyIdentifierForDisplay;
if (fetch != null)
{
IList<string> emailAddresses = fetch.Attributes[WellKnownAttributes.Contact.Email].Values;
string email = emailAddresses.Count > 0 ? emailAddresses[0] : null;
//don't show the email - it's creepy. Just use the name of the email
name = email.Substring(0, email.IndexOf('#'));
}
else
{
name = name.Substring(0, name.IndexOf('.'));
}
//FormsAuthentication.SetAuthCookie(name, false);
SetCookies(name, name);
AuthAndRedirect(name, name);
if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
case AuthenticationStatus.Canceled:
ViewData["Message"] = "Canceled at provider";
return View("Logon");
case AuthenticationStatus.Failed:
ViewData["Message"] = response.Exception.Message;
return View("Logon");
}
}
return new EmptyResult();
}
ActionResult AuthAndRedirect(string userName, string friendlyName)
{
string returnUrl = Request["ReturnUrl"];
SetCookies(userName, friendlyName);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
There are several questions like yours already on StackOverflow. This one seems particularly similar.
If you're already using the Membership provider for your site and are just adding OpenID to it, then I guess you're stuck with Membership for now and can use one of the answers to the question I linked to to get a semi-decent membership provider that MAY work for you.
But if you're writing a new site and just want "use roles and save a user name for the user in my tables" as you said, then DON'T use ASP.NET Membership at all. It's SO not worth it! It doesn't fit OpenID's password-less paradigm and just causes more grief than anything else. If you're not afraid of a little bit of database access yourself, do it that way. And you can get Roles behavior very easily by just issuing your own FormsAuthentication.RedirectFromLoginPage or FormsAuthentication.SetAuthCookie call and passing in the roles the user fills.
The open id provider will return data about the user. If you don't request/require specific tokens of information, then all you'll be given is the user's display name and identity URL.
Depending on what open id library you're using, you can request tokens like FirstName LastName, DOB (if you really cared) and if the user provided that information on their chosen identity, then you'd get it returned to you.
You can then use this to create a new user in the membership system. You'll probably have to give them a dummy password to get around the requirements of the Membership API.
To validate a login, provide 1 form that takes username & password and the other that takes an identity URL. After you've validated the user via open id, try to find the user by username (identity url) in the Membership API. If it doesn't exist, create it.