How to check if windows NT user is valid?

634 views Asked by At

I am creating db users via a web application like so:

        try
        {
            SetConnection(server);
            string sql =
                "USE [master]" +
                " CREATE LOGIN" + " [TP1\\" + user + "] FROM WINDOWS WITH DEFAULT_DATABASE=[master], " +
                "DEFAULT_LANGUAGE=[us_english] " +
                "EXEC sys.sp_addsrvrolemember @loginame = N'TP1\\" + user + "', @rolename = N'sysadmin'";


            _tableContext.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, sql);

        }
        catch (Exception e)
        {
            // log error
            throw e;
        }

and it works fine.

I was testing the application and typed in a name that does not exist in WINDOWS-NT and got the followiing error:

Windows NT user or group 'TP1\MyName' not found. Check the name again.\r\n'TP1\MyName' is not a valid login or you do not have permission.\r\nChanged database context to 'master

After some time researching I found that I can SELECT * FROM sysusers BUT this only shows me if a user is already registered on that server.

I would like to know if there is a way for me to check if the username is a valid NT-user?

1

There are 1 answers

0
ThunD3eR On

This question will be marked as a duplicate but for the purpose of being clear I just wanted to share my specific scenario:

I found the answer here thanks to @SteveDrake.

My implementation :

        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
            {
                user = "MyName";
                UserPrincipal up = UserPrincipal.FindByIdentity(
                    pc,
                    IdentityType.SamAccountName,
                    user);

                bool UserExists = (up != null);
            }

NOTE I changed the ContextType to Domain