Recognize user already logged in C# WPF - c#

I have created the registration and login form. Both work perfectly. But how do i recognize the user logged in as the PHP does by using SESSIONS and COOKIES. I can use static class to get data between different pages, but how can i retrieve the logged user data if he closes the application.
Is there any way for achieving this?
Thanks!

I'm assuming that you want something like instant messenger applications like Skype, or cloud storage applications like DropBox, OneDrive or Mega do. They ask you to enter user name and password once, and then start automatically without asking for user's credentials again.
They achieve this by storing user name and password in encrypted format in the file they normally keep in application folder under specific user account. See the following link for details: How can I get the current user directory?
This is standard practice, as another user will not be automatically logged into your app, if they not entered their own credentials.
Make sure you encrypt the user name and password or the whole file before saving it to disk, otherwise it may become an easy target for password stealing malware.

You should use user settings to do this, as this mechanism hides all the necessary work for creating files in the right locations, etc. from the developer. It works fine and it is made for stuff like this.
You design them in Visual Studio in the project properties on the "Settings" tab. Make sure to select the settings type correctly, as application settings are read-only.
Assume you have to settings UserName and UserPassword. Then, in your code, you could do this:
if (String.IsNullOrWhitespace(Properties.Settings.Default.UserName))
{
// USER NEEDS TO LOG IN
string userName;
string password;
if (Login(out userName, out password))
{
try
{
Properties.Settings.Default.UserName = Encrypt(userName);
Properties.Settings.Default.Password = Encrypt(password);
Properties.Settings.Default.Save();
}
catch (Exception exp)
{
...
}
}
}
else
{
// USER IS ALREADY LOGGED IN
}
private bool Login(out string userName, out string password) would be a method that shows a login user interface and returns true on success or false on failure.
private string Encrypt(string input) would be a method to encrypt a string.

Related

Is there a way to authenticate UWP app with razor-pages created accounts?

First, I am pretty new to C# and sorry for the bad writing, I have a razor page web app with individual accounts authentication type. Now I am working on a UWP app in which users can log in to the UWP app with the username and password provided in the razor app. Users have the same username and password for both applications.
Is there any possible way to log in user to the UWP app and also limit users to access different parts of the app just like razor pages(Role manager)?
Please note that the razor app is on a local server (on-premise), not a cloud, also the UWP app is on the same network so it can access the database.
What is expected to happen is that users must provide a username and password in the UWP app, they have limited access based on their roles, user names and passwords are fetched from the razor page application Db, UWP app doesn't need the ability to create or edit user accounts(it's all managed by razor app)
Update
Please be more specific about your question next time.
if you want to hash the password in UWP apps, you could use HashAlgorithmProvider Class to hash the text. The HashAlgorithmProvider class support MD5,SHA1,SHA256,SHA384,SHA512. You could choose the same way as you choosed in your razor app.
The sample code looks like this:
public string SampleHashMsg()
{
string strAlgName = HashAlgorithmNames.Md5;
string strMsg = "thisistest";
// Convert the message string to binary data.
IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(strMsg, BinaryStringEncoding.Utf8);
// Create a HashAlgorithmProvider object.
HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);
// Demonstrate how to retrieve the name of the hashing algorithm.
string strAlgNameUsed = objAlgProv.AlgorithmName;
// Hash the message.
IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);
// Verify that the hash length equals the length specified for the algorithm.
if (buffHash.Length != objAlgProv.HashLength)
{
throw new Exception("There was an error creating the hash");
}
// Convert the hash to a string (for display).
string strHashBase64 = CryptographicBuffer.EncodeToHexString(buffHash);
// Return the encoded string
return strHashBase64;
}
Old
Your post contains many questions. Please focus on question in one post next time.
First, you need to check the document: Use a SQL Server database in a UWP app. This tutorial shows the steps about how to connect to a sql server in UWP apps. Then you will have to write your own logic for checking the input for username and password and verify it with the data in the database.
After that, you might need to create a userinfo class which contains a flag that could indicate the role or the user after you verified the user. Before navigation, you could check the flag do decide if the user could access the page. If not, then cancel the navigation.

C# Ask for Domain Admin credential and use them to perform some task

I need some help with examples how to use Credential of a current user running application.
So in windows 7 you can run application using user loged in by simply running application or you can use "Run as a different User" option and run it as another user.
In my Active Directory I have 2 account Domain User and one with Domain Admin rights. I'm login Windows as a Domain User and when I need I'm using "Run as a different User" to launch some task as a Domain Admin.
So the task is to get my Credential and use it to perform some task, lets say rename active directory user name.
Best way to do this as I can see is to ask user running application to enter Domain Admin credential on then start application and use them for various task. Of course I can easily run application with "Run as a different User" but I still need to get this credential and use them.
I've searched through the web and I can't find this, all i could find is using credential for a web auth.
If you can show me some examples how to:
1) Ask user for a Admin user credential ( i can leave without this )
2) Get and use credentials of a user running application
I don't want to know password I know I can't. Don't really want to add to a WPF form password box I prefer to use windows API to handle this i've already entered user name and password using "Run as a different User".
PS: I sorry if this topic exists :( I guess I'm bad at creating correct search requests.
ADDED: to be more clear what I need. In powershell it will look like this:
# This Asks user to enter credentials
$cred = Get-Credential;
# this checks if I have rights to use them.
Get-ADDomain “DOMAIN” –Server “Domain.com” –Credential $cred;
Of course it's simplified as hell though the point is that I can use credentials user entered when ever it's needed.
The equivalent C# to your Get-ADDomain is quite simple, it is just
public void PerformSomeActionAsAdmin(string adminUsername, string adminPassword)
{
//Null causes the constructor to connect to the current domain the machine is on.
// |
// V
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, adminUsername, adminPassword))
{
//do something here with ctx, the operations will be performed as whoever's username and password you passed in.
}
}
if you don't want to connect to the current domain and instead want to connect to Domain.com then replace the null with the appropriate string.
EDIT: if you want to use secure strings you can't use System.DirectoryServices.AccountManagement.PrincipalContext, you will need to go with the lower level calls in System.DirectoryServices.Protocols. Doing this process is quite complex, here is a link to the MSDN article "Introduction to System.DirectoryServices.Protocols (S.DS.P)" explaining how to use it. It is a big complex read and honestly I don't think it is worth it to be able to use encrypted strings.
public void PerformSomeActionAsAdmin(NetworkCredential adminCredential)
{
using(LdapConnection connection = new LdapConnection("fabrikam.com", adminCredential))
{
// MAGIC
}
}
Do you want to check if the current user is a doman admin? start by looking at his code, it should help you get started identifying what AD groups the current user is in. This will give you a list of strings that are each group's name the current user belongs to. Then you can check that list against whatever AD group you are trying to check for. Replace YourDomain with your domain name:
WindowsIdentity wi = WindowIdentity.GetCurrent();
List<string> result = new List<string>();
foreach (IdentityReference group in wi.Groups)
{
result.Add(group.Translate(typeof(NTAccount)).ToString().Replace("YourDomain\\", String.Empty));
}
Since i'm not quite sure what you're trying to do, this also might be helpful. You'd have to get the user name and password from a textobx, password box etc. This could be used for an "override" to use, for example, a manager's credentials etc. to do something the current user wasn't allowed to do because of AD group membership etc.
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YourDomain"))
{
if (UserName.Contains("YourDomain\\"))
{
UserName = UserName.Replace("YourDomain\\", String.Empty);
}
//validate the credentials
bool IsValid = pc.ValidateCredentials(UserName, Password);
}

Get current user's name and user id

I dont do aspx at all so trying to work out this simple task.
I see the following code in some cs files which guess gets the current user and i assume this is a standard method in asp but might be wrong:
CS:
User user = (User)Context.Items["CurrentUser"];
I have tried things like this from other posts on here but maybe this system is different or the setup is different? again i dont know.
var currentUser = Membership.GetUser(User.Identity.Name);
string username = currentUser.UserName; //** get UserName
Guid userID = currentUser.ProviderUserKey; //** get user ID
Does anyone know how i can get the Name and User ID of the current user based on what is written above?
it depends on how you handle users in your website.
if you use the asp.net built in user management, then User.Identity.Name will get you the currently logged in username.
other stuff like (User)Context.Items["CurrentUser"] or (User)Session["myUser"] will get you the user which was saved in those places somewhere in your website.
you just need to start your way from the login page, and follow the functions to see how users are being handled in your website.

Log In User with Parameters when Changing Password

I have an ASP.NET App in which want to send an email to a user that presses a Recover Password button that resets the user's password and then sends a link to the user that when followed will log the user in with a new password and bring them to the Change Password page where they must resent their password.
I'm able to reset the password and get the new randomly generated password that I send back to the user in an email. However, when the user follows the link back with the UserName and pw parameters, the system does not seem to log them in,
Here's the code I am using on the load event that does not seem to work:
try
{
string sUserName = Request.QueryString["UserName"].ToString();
string sPw = Request.QueryString["pw"].ToString();
if (Membership.ValidateUser(sUserName, sPw))
{
//Log the user in???
FormsAuthentication.Authenticate(sUserName, sPw);
}
}
catch (Exception r)
{
string sMessage = r.Message;
}
Any help in logging the user in with username and password parameters would be greatly appreciated.
You can use FormsAuthentication.SetAuthCookie() :
if (Membership.ValidateUser(sUserName, sPw))
{
FormsAuthentication.SetAuthCookie(sUserName, true);
}
In your sample code you are retrieving the user name and password from the query string - this is very bad practice as any observer will see it in plain text. At least use a POST for these values and put them in the body (i.e with a form POST) and always use HTTPS at least for your login page.
use the following code.
if (Membership.ValidateUser(sUserName, sPw))
{
FormsAuthentication.SetAuthCookie(sUserName, true);
Response.Redirect("ChangePassword.aspx");
}
FormsAuthentication.Authenticate is almost same as FormsAuthentication.ValidateUser. They just validate user authentication. SetAuthCookie creates the authentication ticket(login).
This is how (IMO) reset password functionality should work:
User clicks button saying "Forgot Password".
In your code store a random GUID in the DB.
Send the user an email, with the GUID as a link in the email, as well as their userid, e.g:
http://yoursite.com/user/reset?guid=a21312738&userid=213123
On the incoming page, read the userid from the QS, and fetch the user from the DB by this value.
Compare the stored GUID from the GUID in the QS. If success, render a form that allows the user to change the password via an HTTPS POST.
In the POST action, change the user's password and sign them in.
You could also go one step further and store an expiration date for the GUID (e.g user must change their password in 24 hours).

User account name not updating in c# WinForm Application

I am editing a c# WinForm solution and I do not understand the code that gets the user account name. The code is shown below.
The application shows a customized form for each user account and the user account name is needed to get user-specific configuration values from an SQL database.
What happens, to the best I can tell, is the returned user name is correct for the first user account accessed, but after switching to a different user account, the returned user account name is not updated and the initial user account name continues to be returned.
#region "Function to retrieve LoggedIn user"
/// <summary>
/// "Function to retrieve LoggedIn user"
/// </summary>
/// <returns></returns>
private string GetLoggedInUserName()
{
ManagementClass objManClass = new ManagementClass("Win32_Process");
ManagementObjectCollection arrManObjects = objManClass.GetInstances();
foreach (ManagementObject objMan in arrManObjects)
{
if (objMan["Name"].ToString().Trim().ToLower() == "explorer.exe")
{
string[] arrArgs = { "", "" };
try
{
objMan.InvokeMethod("GetOwner", arrArgs);
sUserName = arrArgs[0];
break;
}
catch (Exception lExp)
{
BusinessObject.Logger.Logger.Log(lExp);
}
}
}
return sUserName;
}
#endregion
This application is to run on XP, Vista and 7.
My instinct is to just use something like...
string sUserName = Environment.UserName;
...but my knowledge of the Windows OS is poor and the people who wrote the original code are much smarter than me.
So my two questions are:
(1) Why does this code appear to not update to the new user name when I change user accounts?
(2) why use the 'explore.exe' method instead of simply using 'Environment.UserName'?
Also, two projects in my solution have a GetLoggedInUserName()method. One project runs in the background with a timer that calls the other project, and that project generates the user-customized form.
I have another related question about why the form fails to appear for all user accounts except the admin account that I will post as a separate question once I figure out this question.
If you want the currently logged in user, use can use the WindowsIdentity object:
string currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
The Explorer process is always running when you log onto a Windows box, so it will always be found. If you open Task Manager and view the processes you will see it, and the account that started it. It looks like a throw back to VBScript, although I'm sure that there is an easier way to it with that too.
There is no good reason to use WMI to get the current user account on a local machine over other simpler methods.
For the user name bit try ...
string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

Categories

Resources