The following C# code accepts two parameter username and password from API using ajax
public Login[] checkLogin(models.Login log)
{
Boolean flag = false;
connection obj = new connection();
IMongoDatabase server = obj.getConnection();
var collection = server.GetCollection<models.Login>("login");
string param = "{'username':'" + log.username + "','password':'"+ log.password +"'}";
List<Login> result = new List<Login>();
var check = collection.Find(param);
foreach(var emp in check.ToList())
{
result.Add(emp);
}
if(result == null)
flag = false;
else
flag = true;
return result.ToArray();
}
I want to check the username and password from my MongoDB database. I am trying to find method but don't know how to check the value if it is available or not.
In order to test whether provided credentials are valid, your method should simply return a boolean value.
You might do something like this.
public IMongoCollection<models.Login> GetLoginCollection()
{
var client = new MongoClient();
var database = client.GetDatabase("dbName");
var collection = database.GetCollection<models.Login>("login");
return collection;
}
public bool CheckLogin(models.Login log)
{
var collection = this.GetLoginCollection();
var authSuccessful = collection
.Count(login =>
login.username == log.username &&
login.password == log.password) > 0;
return authSuccessful;
}
As an alternative, CheckLogin() method might be implemented using explictly-defined filters.
public bool CheckLogin(models.Login log)
{
var collection = GetLoginCollection();
var filter = Builders<models.Login>.Filter
.And(
Builders<models.Login>.Filter.Eq(login => login.username, log.username),
Builders<models.Login>.Filter.Eq(login => login.password, log.password));
var authSuccessful = collection.Count(filter) > 0;
return authSuccessful;
}
Note that storing clear text password within the database is a bad practice. Nobody but the user should know the actual password. One solution is storing the hashed password in the database. On authentication you can compare the hash of the provided password with your stored value. One of the most common hash functions is md5.
Related
I am new to c# and .net api. I am doing a login method where if a user is found in database, it will return the user.The user object is likethis,
{ email: user#email.com, password: password, name: User Name, }
First thing, I want to remove the password from the return object, second I want to add the JWT token to the return object. Here is my code:
public object LoginCurrentUser(User user) {
var result = AuthenticateUser(user);
if (result != null)
{
var token = Generate(user);
//I want to create new variable here that removes the password and adds the token to the field.
return result;
}
else {
return null;
}
}
It should be pretty straight forward.
if (result != null)
{
var token = Generate(user);
var response = new {
Email = result.Email,
Name = result.Name,
Token = token
};
return response;
}
Alternatively, You can create a DTO class for the response and return its object.
I got this register form where i get the user email and password and hash the password using SHA512
public Boolean IsRegistered(String email, String pass)
{
SHA512 shaM = new SHA512Managed();
if (pass.Length > 0 && email.Length > 0)
{
byte[] data = Encoding.UTF8.GetBytes(pass);
String encryptedpass = Encoding.UTF8.GetString(shaM.ComputeHash(data));
using (ModelContainer db = new ModelContainer())
{
//User usr = db.UserSet.Where(u => u.PasswordDigest == encryptedpass && u.Email == email).First();
int matches = (from u in bd.UserSet
where u.PasswordDigest == encryptedpass&& u.Email == email
select new
{
Id = u.Id
}
).Count();
if (matches > 0)
{
return true;
}
}
}
return false;
}
I use this method each time the user logs in and it works like a charm (i guess),
thing is when i prompt the user to change his/her password i cannot seem to be able to validate the old one here is what i try
I do the following to retrive the user data on the MyAccount form's constructor
User user;.
public MyAccount()
{
InitializeComponent();
try
{
using (ModelContainer db = new ModelContainer())
{
user = (from u in db.UserSet where u.Id == 2 select u).First();
txtName.Text = user.Name;
txtEmail.Text = user.Email;
}
}
catch (Exception x)
{
ErrorAlert error = new ErrorAlert("Error: " + x.Message);
error.Owner = getParentWindow();
error.ShowDialog();
}
}
then I validate it on the forms button_click
using (ModelContainer db = new ModelContainer())
{
SHA512 shaM = new SHA512Managed();
string oldpass = Encoding.UTF8.GetString(shaM.ComputeHash(Encoding.UTF8.GetBytes(ptxtOldPassword.Password)));
shaM.Dispose();
db.UserSet.Attach(user);
Regex rgx = new Regex(#"\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z");
if (rgx.IsMatch(txtEmail.Text))
{
if (oldpass == user.PasswordDigest)
{
if (ptxtNewPassword.Password.Equals(ptxtNewPassword2.Password))
{
string newpass = Encoding.UTF8.GetString(shaM.ComputeHash(Encoding.UTF8.GetBytes(ptxtNewPassword.Password)));
user.Name = txtName.Text;
user.Email = txtEmail.Text;
user.PasswordDigest = newpass;
db.SaveChanges();
}
else
{
ErrorAlert error = new ErrorAlert("Passwords do not match");
error.Owner = getParentWindow();
error.ShowDialog();
}
When I comapare the old password in the database with the one the user enter they do not match since they are strings I've tried using equals with no luck I thought == would work but I was wrong, i looked into other answers and found this Sha512 not returning equal in c# hash validation sadly it didn't work for me, I need to understand why my first validation work and the second doesnt
so any help is apreciated Have a nice day
You don't really need to compare the final strings, test at the bytes-level. Check this previous question.
Also, if you already validated the existence of the user (by email or any other mechanism), why don't just change / update with the new password? You could validate with the email and re-use the working function for login / signin.
I have created a AD forest that search for a user across all domains in the forest using its global catalog connection string.
I am trying to get thumbnailPhoto of AD user using c# code. But I did not get thumbnailPhoto property in result object even though it exist in AD.
I had verified the thumbnailPhoto prop in AD using powershell. Also I have verified it by getting using LDAP connection string. It both case I got the byte array.
Below is the code to get user and its properties and _configuration.GlobalCatalog returns the Global catalog connections string which is in format (GC://domain-name).
public Task<ProfileImage> GetProfileImageByEmail(string email)
{
var filterQuery = ("mail=" + email);
return Task.FromResult(GetProfileImageFromAD(filterQuery));
}
private ProfileImage GetProfileImageFromAD(string filterQuery)
{
var result = GetADUserDetails(filterQuery);
if (result == null)
return null;
if (result.Properties.Contains("thumbnailPhoto"))
{
var imageBytes = result.Properties["thumbnailPhoto"][0] as byte[];
if (imageBytes != null)
{
return new ProfileImage
{
Content = new MemoryStream(imageBytes),
ContentType = "image/jpeg"
};
}
}
return null;
}
private SearchResult GetADUserDetails(string filterQuery)
{
using (var userBinding = new DirectoryEntry(_configuration.GlobalCatalog))
{
using (DirectorySearcher adSearch = new DirectorySearcher(userBinding))
{
adSearch.ReferralChasing = ReferralChasingOption.All;
adSearch.Filter = filterQuery;
adSearch.PropertiesToLoad.Add("mail");
adSearch.PropertiesToLoad.Add("sn");
adSearch.PropertiesToLoad.Add("givenName");
adSearch.PropertiesToLoad.Add("thumbnailPhoto");
return adSearch.FindOne();
}
}
}
Any help is appreciated.
Update:
On a domain controller open ADSIEdit, connect to Schema Naming Context, find attribute CN=Picture,CN=Schema,CN=Configuration... and go to it's properties. Verify that isMemberOfPartialAttributeSet is set to TRUE
I am trying to create a login method and I need to get a password from the corresponding user. This is my database layer code:
public int loginUser(string userName, string pass)
{
int result = 0;
var credentials = MongoCredential.CreateMongoCRCredential("SearchForKnowledge", userName, pass);
var settings = new MongoClientSettings
{
Credentials = new[] { credentials }
};
try
{
var mongoClient = new MongoClient(settings);
var database = mongoClient.GetDatabase("SearchForKnowledge");
var coll = database.GetCollection<BsonDocument>("Users");
var filter = Builders<BsonDocument>.Filter.Eq("userName", userName);
var query = coll.Find(filter);
//??????????
}
catch (Exception ex) {
result = 0;
}
return result;
}
as you can see if the login is success im trying to return 1 and if it fails, 0 (for redirecting purposes). I am struggling to check if the username matches password set to it. At the moment I just made a filter, passed it to the method Find and im dead stuck at this point. How do I return that user's password from mongodb and compare it to the one passed as a parameter?
Try something like this:
public int loginUser(string userName, string pass)
{
int result = 0;
//Here you use credentials for the connection, not the one passed
//to the method:
var credentials = MongoCredential.CreateMongoCRCredential("SearchForKnowledge", connectionUsername, connectionPass);
var settings = new MongoClientSettings
{
Credentials = new[] { credentials }
};
try
{
var mongoClient = new MongoClient(settings);
var database = mongoClient.GetDatabase("SearchForKnowledge");
var coll = database.GetCollection<BsonDocument>("Users");
var filter = Builders<BsonDocument>.Filter.Eq("userName", userName);
var result = await coll.Find(filter).ToListAsync().First();
if(result["Password"] == pass)
{
result = 1;
}
}
catch (Exception ex) {
result = 0;
}
return result;
Here is my code:
This is the function being called by fiddler using:
http://localhost:3334/Service/Login/?json={'username':'cara','password':'password'}
public ActionResult Login(JObject JSON)
{
var response = JsonResponse.OKResponse();
var username = JSON["username"].ToString();
var password = JSON["password"].ToString();
var helper = new MemberHelper();
//goes into here and never returns
if (helper.ValidateUser(username, password))
{
MongoCollection<User> users = db.GetCollection<User>();
var usr = users.FindAll().FirstOrDefault(u => u.UserName.Equals(username));
response.data.Add(usr);
}
else
{
return Json(JsonResponse.ErrorResponse("Invalid username or password provided!"), JsonRequestBehavior.AllowGet);
}
return Json(response, JsonRequestBehavior.AllowGet);
}
And the validateUser method within MemberHelper:
public override bool ValidateUser(string username, string password)
{
var hash = Encoding.ASCII.GetBytes(password);
var provider = new SHA256CryptoServiceProvider();
for (int i = 0; i < 1024; i++) // 1024 round SHA256 is decent
hash = provider.ComputeHash(hash);
var pass = Convert.ToBase64String(hash);
MongoCollection<User> users = db.GetCollection<User>();
//***The following statement is where the program just stops***
var usr = users.FindAll().FirstOrDefault(u => u.UserName.Equals(username) && u.Password.Equals(pass));
...
}
And getCollection....
public MongoCollection<T> GetCollection<T>(string name = null)
{
string collectionName = name;
if (collectionName == null) {
collectionName = typeof(T).Name;
}
return Database.GetCollection<T>(collectionName);
}
I really don't know what is going wrong. I am new to linq so I am not sure if there is some golden rule that I am breaking. Please help! Let me know if there is anything else I need to add.
You can also change it to something like
var usr = users.AsQueryable().Where(u => u.UserName.Equals(username)).FirstOrDefault();
The problem was indeed within the method GetCollection<>() once I replaced it with the following code, it worked just fine:
public MongoCollection<T> GetCollection<T>(string name = null)
{
string collectionName = name;
if (collectionName == null)
collectionName = typeof(T).Name;
if (Database.CollectionExists(collectionName) == false)
Database.CreateCollection(collectionName);
return Database.GetCollection<T>(collectionName);
}