I would like the feature for the sign in box to have the username and password automatically filled in if the user has previously been on the site and logged in successfully before. I see this implemented on many sites so I figured theres a way to do this without creating a security risk.
EDIT: According to a post this is a browser feature and should not be implemented in code because its never safe to store password anywhere.
Edited the code to reflect a new direction where Im only storing the username. However, Im not sure what to look for to see if its working. I tried to login then logout, then go to login screen again but username box still blank when the view loads in. Not sure if its the code or Im testing it the wrong way.
Login POST:
[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return Json(new { ok = true, message = "Login successful." });
}
}
return Json(new { ok = false, message = "The username or password you entered is invalid. Please try again." });
}
Login GET:
[HttpGet]
public ActionResult Login(string path)
{
LoginModel model = new LoginModel();
HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName.ToString()];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null & !authTicket.Expired)
{
model.UserName = authTicket.UserData;
}
}
return PartialView(path, model);
}
There are couple of issues with your code. The first one is that you are adding the cookie to the Request object instead of adding it to the Response => Response.Cookies.Add(authCookie);.
The second issue is that you are creating a non-persistent cookie meaning that it will only live through the browser session. Once the user closes the browser it will be gone forever because it was never stored on the client computer. In order to create a persistent cookie you need to specify an expiration date for it which will obviously correspond for how long this cookie will be persisted on the client computer. For example if you wanted to remember for 5 days:
HttpCookie authCookie = new HttpCookie("authCookie", "cookieValue")
{
Expires = DateTime.Now.AddDays(5)
};
Another issue is that you are storing only the MD5 hash of the password inside the cookie and you expect to be able to decrypt it later with FormsAuthentication.Decrypt which is not possible. This method can decrypt values that were encrypted with the Encrypt method.
And the biggest problem of them all is the security: you should never be storing any password related stuff anywhere. The username should suffice. Browsers offer the possibility to remember passwords for given site. I would recommend you using this functionality instead of doing what you are doing.
Another possibility is to emit a persistent authentication cookie when the user logs in, so that even if he closes the browser he will be remembered as authenticated for the validity period you specified in this authentication cookie.
you don't need the actual password for the user to make sure he logged in previously. You shouldn't even save the actual password in the database. You usually only save a salted hash of that password. When the user logs in, you create a hash for that password and compare it with the hash stored in the database. If they match, he entered the correct password.
As for storing login information in a cookie, i'd then store a salted hash of that password hash in the cookie. Upon GET, you just create a salted hash of the stored password hash and compare it with the one from the cookie. If they match, the login cookie is valid. That way you never actually store any user password anywhere.
To make this more secure, the login page should be secured by SSL, otherwise the password would at least once be transmitted unencrypted.
If you're using SQL, you can generate a random number when the user first logs on. Store this number in the Users table, and also as a cookie on the user's machine. The user can then authenticate by comparing the random number with that stored on the server.
It's a good idea to timestamp the login though, so it expires after a set period of time.
Related
I need to validate user credentials from external service, therefore I'm using the VirtualUser authentication.
BuildVirtualUser, checking for the roles to set to him, saving the user Profile and then login with that name.
I'm facing a problem, that everyday that i login, with the same credentials Sitecore creates a new user in Experience Profile.
What i need to change in my code to assure that, with virtual user login, Sitecore gets the old experience profile of the user?
I was thinking in creating the user in sitecore with same generic password. Instead of using the virtual user, and authenticate directly with sitecore. Is that correct?
Here's my code:
Sitecore.Security.Accounts.User user = Sitecore.Security.Authentication.AuthenticationManager.BuildVirtualUser(sitecoreUser, true);
string roleName = #"newRole\User";
Sitecore.Security.Accounts.Role demoRole = Sitecore.Security.Accounts.Role.FromName(roleName);
if (Sitecore.Security.Accounts.Role.Exists(roleName) && !demoRole.IsMember(user, true, false))
{
user.Roles.Add(Sitecore.Security.Accounts.Role.FromName(roleName));
}
user.Profile.Name = name;
user.Profile.Email = email;
user.Profile.FullName = fullname;
user.Profile.Save();
Sitecore.Security.Authentication.AuthenticationManager.Login(user.Name);
Tracker.Initialize();
Code looks fine, but you miss one important thing: to identify your user/contact.
You need to add next line of code:
Tracker.Current.Session.Identify(email);
Please check next link to find more information about how to identify contacts:
https://doc.sitecore.net/sitecore_experience_platform/setting_up__maintaining/xdb/contacts/identifying_contacts
I'm building a restricted signup. I want user with a specific code passed in a url to be able to signup and not others. I'm using the accounts package.
I can prevent account creation in the Accounts.onCreateUser method. I'm looking for a way to tell the server if the client had an authorised signup code. With a classic form (email+password) I can just add an extra hidden field. How can I achieve the same result if the user signs up with let's say Facebook?
Since Meteor doesn't use cookies, I can't store this info in a cookie that the server would access. Session variable are not accessible server side. And since I'm not controlling what got send with the account-facebook creation, I can't use a Session variable on the client side that I'd pass along when the user presses sign up.
Any idea"?
Just add the special token to the user object being passed to Accounts.createUser():
var user = {
email: email,
password: password,
profile: {
token: token
}
};
Accounts.createUser(user, function (error, result) {
if (error) {
console.log(error)
}
});
On the server side you can access this in the Accounts.onCreateUser():
Accounts.onCreateUser(function(options, user) {
console.log(options);
console.log(user);
});
I think it's in the options variable that you will find your token, so it would be options.profile.token.
for me, the best option here was passing in custom parameters to loginbuttons.
see the package docs:
https://github.com/ianmartorell/meteor-accounts-ui-bootstrap-3
Where it outlines the below:
accountsUIBootstrap3.setCustomSignupOptions = function() {
return {
mxpDistinctId: Session.get('mxpdid'),
leadSource: Session.get('leadSource')
}
};
I'm using Parse.com and trying to set up user sign up with Facebook.
Upon authentication with Facebook for the first time a beforeSave is called on _User to fetch additional user details:
function UserBeforeSave(request, response){
var user = request.object,
auth = user.get('authData');
// check if user is newly registered
if (!user.existed()) {
// Check if a user signs up with facebook
if (Parse.FacebookUtils.isLinked(request.object)) {
// Query Graph API for user details
Parse.Cloud.httpRequest({
url:'https://graph.facebook.com/v2.2/me?access_token=' + auth.facebook.access_token,
success:function(httpResponse){
// Map facebook data to user object
if (httpResponse.data.first_name) request.object.set('first_name', httpResponse.data.first_name);
if (httpResponse.data.last_name) request.object.set('last_name', httpResponse.data.last_name);
if (httpResponse.data.email) request.object.set('email', httpResponse.data.email);
response.success();
},
error:function(httpResponse){
console.error(httpResponse);
response.error();
}
});
} else {
response.success();
}
} else {
response.success();
}
}
Problem is that that email line is actually breaking the operation with error:
Can't modify email in the before save trigger
I tried moving this code to the afterSave but the authdata is not available there making it difficult to call the FB API. The email is therefore left blank at the moment.
I'm assuming this is a very common use case of integrating Parse with the Facebook API, am I missing something in the integration process that automatically fetches the email?
I just do the graph query client-side and set email there. This works fine.
Is there a reason you want to do it in the before/afterSave on the User?
Goal: I'm trying to get a Ruby on Rails application to send me emails whenever a user fails to log into OmniAuth. I want the e-mail to include (1) the username entered in the form, and (2) an MD5 hash of the password field.
Obstacle: OmniAuth returns a POST after a successful login, and a GET after an authentication failure. The "success" POST includes the username and a filtered password, but the "fail" GET does not include these two parameters.
So I guess my question is "Can I make OmniAuth return the parameters I want? If not, how can I make Rails remember the form data after it gets POST'ed to OmniAuth?"
I emailed the OmniAuth team and they gave me the solution below (thank you so much!):
You can do custom failure handling by adding an on_failure action.
OmniAuth.config.on_failure = Proc.new { |env| #do stuff }
https://github.com/intridea/omniauth/blob/master/lib/omniauth/failure_endpoint.rb
is the default failure endpoint as an example
So I added the following in config/initializers/omniauth.rb:
OmniAuth.config.on_failure = Proc.new{|env|
myLog = ActiveSupport::TaggedLogging.new(Logger.new("log/omniauth_log.txt"))
myLog.tagged("OmniAuth", "ENV") { myLog.info "Failed login attempt - username: #{env["rack.request.form_hash"]["username"]}, password: #{env["rack.request.form_hash"]["password"]} "}
OmniAuth::FailureEndpoint.new(env).redirect_to_failure}
...and it records the username and password correctly. All that's left to do is encrypt the password.
If you want to display everything that's going on, you can log #{env.inspect} itself. It's a very large hash though (that also contains smaller hashes), so maybe log #{env.inspect} once and pick out the fields relevant to your task.
For one of our FBA enabled SharePoint site, we need to access various web services. I know that we need to invoke Authentication.asmx before we make any other SP web service call.
How do I get the currently logged in user's username & password to pass to the Authentication.asmx service?
Thanks.
Update: I tried Marek's solution with a known username and password and got a 401 for Authentication.asmx. So probably some settings are off. The admin is looking into it.
MembershipUser user = Membership.GetUser();
string username = user.UserName;
string password = user.GetPassword();
Authentication auth = new Authentication();
auth.CookieContainer = new CookieContainer();
LoginResult result = auth.Login(username, password);
if (result.ErrorCode == LoginErrorCode.NoError)
{
CookieCollection cookies = auth.CookieContainer.GetCookies(new Uri(auth.Url));
Cookie authCookie = cookies[result.CookieName];
Lists lists = new Lists();
lists.CookieContainer = new CookieContainer();
lists.CookieContainer.Add(authCookie);
lists.GetListCollection();
}
However, depending on the settings of the membership provider (is password stored in plain text, encrypted or hashed? is it required to pass the security answer to get the password?) retrieving the password may be more difficult or even impossible and you will need to ask the user for it.