logo
down
shadow

Creating Windows authentication and SQL Server authentication in login form


Creating Windows authentication and SQL Server authentication in login form

Content Index :

Creating Windows authentication and SQL Server authentication in login form
Tag : chash , By : Lee KW
Date : November 23 2020, 03:01 PM

like below fixes the issue I'm only posting this answer since OP can't seem to make @Tim's answer work. Credits to @Tim.
Just simply use:
private void btn_Login_Click(object sender, EventArgs e)
{
    bool useWindowsAuth = WindowsAuth.Checked; // Assuming that WindowsAuth is your radio button

    string userName = string.Empty;
    string password = string.Empty;

    if(!useWindowsAuth)
    {
        userName = textBox1.Text;
        password = textBox2.Text;

        if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
        {
            MessageBox.Show("Please provide Username and Password");
            return;
        }
    }

    var connStrBldr = new System.Data.SqlClient.SqlConnectionStringBuilder();
    connStrBldr.DataSource = @"172.28.40.19\CASINO2008R2";
    connStrBldr.InitialCatalog = "GCVS2_DEV_GHR";

    if (useWindowsAuth) 
    {
        connStrBldr.IntegratedSecurity = true;
    } 
    else 
    {
        connStrBldr.IntegratedSecurity = false;
        connStrBldr.UserID = userName;
        connStrBldr.Password = password;
    }

    bool validUser = true;

    try
    {
        using (SqlConnection con = new SqlConnection(connStrBldr.ToString())) 
        {
            con.Open();
            //do your lookup on login here
        }
    }
    catch(SqlException) // An exception will be caught if invalid credentials were used.
    {
        validUser = false;
    }

    if(validUser)
        MessageBox.Show("Login successful!");
    else
        MessageBox.Show("Login failed!");    
    }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication


Tag : sql-server , By : Doc Immortal
Date : March 29 2020, 07:55 AM
Hope this helps I had this issue and it was because the machine running the application isnt trusted for delegation on the domain by active directory. If it is a .net app running under an application pool identity DOMAIN_application.environment for example.. the identity can't make calls out to SQL unless the machine is trusted.

What's the difference: Windows Authentication, Passport Authentication and Form Authentication?


Tag : chash , By : Dave
Date : March 29 2020, 07:55 AM
hop of those help? I would say it greatly depends on what your web app will be doing, as each one has its place. Here is some brief details about each one.
Windows authentication enables you to identify users without creating a custom page. Credentials are stored in the Web server s local user database or an Active Directory domain. Once identified you can use the user s credentials to gain access to resources that are protected by Windows authorization.

Couldn't connect SSMS using Windows authentication but can login using SQL Authentication


Tag : sql-server , By : Caleb Ames
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Issue has been fixed, there is a problem with the Active Directory. When we update group policy, issue has been fixed!

Can an MVC 5 application (deployed on Azure) have authentication like windows authentication ( no login page)?


Tag : .net , By : Schmidt
Date : March 29 2020, 07:55 AM
To fix the issue you can do That is absolutely possible, provided that the user is already signed in with the account associated to the azure AD directory the app is configured to use (for example, a user signed in a Windows 10 device with their Azure AD account). There are two main considerations you need to apply:
The URL on which the user lands must require the caller to be authenticated - for example, the controller class or the action must be protected with [Authorize] You must ensure that Azure AD doesn't prompt the user to choose what directory he/she is from, but automatically select their home directory. One way to do that is to pass the domain_hint, as discussed in http://www.cloudidentity.com/blog/2014/11/17/skipping-the-home-realm-discovery-page-in-azure-ad/.

How to check if login program supports windows authentication and sql authentication mode?


Tag : chash , By : socurious
Date : November 10 2020, 03:01 PM
this will help I am currently creating a login program in c# visual studio 2015. The purpose of this program is to allow myself to login into it and then able to execute sql scripts (.sql files). , Use following code to check sql login mode :
DECLARE @AuthenticationMode INT  
EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', 
N'Software\Microsoft\MSSQLServer\MSSQLServer',   
N'LoginMode', @AuthenticationMode OUTPUT  

SELECT CASE @AuthenticationMode    
WHEN 1 THEN 'Windows Authentication'   
WHEN 2 THEN 'Windows and SQL Server Authentication'   
ELSE 'Unknown'  
END as [Authentication Mode]
public bool _MCheckWindowsLogin()
        {
            using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=True;database=master"))
            {
                try
                {
                    con.Open();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool _MCheckSQLLogin()
        {
            using (SqlConnection con = new SqlConnection("ConnectionStringWithSQLLogIN"))
            {
                try
                {
                    con.Open();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool _MCheckLogin()
        {
            if (!_MCheckSQLLogin())
            {
                if (!_MCheckWindowsLogin())
                {
                   MessageBox.Show ("Some Error Message Here");
                    return false;
                }
                using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Integrated Security=True;database=master"))
                {
                    con.Open();
                    try
                    {
                        using (SqlCommand cmd = new SqlCommand("DECLARE @D BIGINT IF NOT EXISTS (SELECT NAME FROM [master].[sys].[syslogins] WHERE name = 'YourLoginName') BEGIN SET @D = 1 END SELECT @D", con))
                        {
                            using (SqlDataReader dr = cmd.ExecuteReader())
                            {
                                if (dr.HasRows)
                                {
                                    while (dr.Read())
                                    {
                                        bool a = Convert.ToBoolean(dr[0]);
                                        dr.Close();
                                        if (a)
                                        {
                                            string Aa = @"EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 2 ;";
                                            Aa += "CREATE LOGIN [YourLoginName] WITH PASSWORD=N'YourPassword', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF ;";
                                            Aa += "EXEC master..sp_addsrvrolemember @loginame = N'YourLoginName', @rolename = N'bulkadmin' ;";
                                            Aa += "EXEC master..sp_addsrvrolemember @loginame = N'YourLoginName', @rolename = N'dbcreator' ;";
                                            Aa += "EXEC master..sp_addsrvrolemember @loginame = N'YourLoginName', @rolename = N'diskadmin' ;";
                                            Aa += "EXEC master..sp_addsrvrolemember @loginame = N'YourLoginName', @rolename = N'processadmin' ;";
                                            Aa += "EXEC master..sp_addsrvrolemember @loginame = N'YourLoginName', @rolename = N'securityadmin' ;";
                                            Aa += "EXEC master..sp_addsrvrolemember @loginame = N'YourLoginName', @rolename = N'serveradmin' ;";
                                            Aa += "EXEC master..sp_addsrvrolemember @loginame = N'YourLoginName', @rolename = N'sysadmin' ;";
                                            using (SqlCommand cmd8 = new SqlCommand(Aa, con))
                                            {
                                                cmd8.ExecuteNonQuery();
                                            }
                                        }
                                        con.Close();
                                        Thread.Sleep(2000);
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception exp)
                    {
                        con.Close();
                        MessageBox.Show(exp.Message);
                        return false;
                    }
                }
            }
            return true;
        }
if (_MCheckLogin())
{
   //Do somthing
}
else
{
   //Do somthing
}
Related Posts Related QUESTIONS :
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Generic event test method, preventing code duplication
  • How do I keep the ellipses in the center when the screen is resized
  • How to require a property using JsonSchema.NET?
  • C# XDocument Element/Elements returns null
  • Autofac keyed service with IEnumerable relationship type
  • Installing EntityFramework via NuGet manager
  • Always Check if there is Internet Connection Xamarin forms
  • WCF OneWay service slows down when aspNetCompatibilityEnabled is set to false
  • Can we use JsonRequestBehavior.AllowGet with [HttpPost] attribute?
  • How to customize the Setup wizard with custom forms in Visual Studio setup project
  • C# ASP.NET - Use method from another class to create labels
  • C# List IList or IEnumerable as argument
  • Parsing File with C# And Replace method
  • Losing special unicode characters in encryption (C#)
  • Getting stored procedure returned value instead of row affected
  • How can I construct HTML using NameValuePair in android?
  • Loading a pop up page in ASP.net through a js file
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com