I am using Linq to sql from c# to connect to sql server in a WCF service. I am using windows authentication to connect to database. I want to use other user windows authentication to connect to sql server from Linq to sql. Is their a way to do that.
-
Why do you want to do that? Are you trying to overcome another problem? Just run the service using an account with permission to connect to the database server or add the service's account to the database. That's the whole point of using Windows Credentials, you don't need to hardcode usernames and passwords. More convenient, more manageable *and* more secure. – Panagiotis Kanavos Feb 17 '15 at 07:59
-
I dont have access for database with my Windows credentials. I have other users windows credentials to access database. With other user credentails i want to access data base in c# temporarily untill iget access to my credentials – user2412130 Feb 17 '15 at 08:11
-
Why don't you run the service with this account then? If you want to use the database during development/debugging, I suggest you clone it (or at least the data you need) and work with a local copy. It's a bad idea to develop against a production database. – Panagiotis Kanavos Feb 17 '15 at 08:28
-
Possible duplicate of [Connecting To A Database Using Windows Authentication With Different Credentials using C#](http://stackoverflow.com/questions/8439517/connecting-to-a-database-using-windows-authentication-with-different-credentials) – Ash Jul 26 '16 at 00:11
1 Answers
From the comments I assume you want to connect to a production database during development for a short period, until your development account gets access to the database.
First of all, don't do this. It's a bad idea for several reasons. Working against a production database is bad.So is writing code that will be removed once you get proper access.
If you only want to test your service, just use the Windows account credentials you already have as the service account.
As a last resort, you can impersonate a specific account using WindowsIdentity.Impersonate. The function's sample shows how to authenticate the user using P/Invoke and the LogonUser Win32 API. You'll have to take care to call Undo
once you are finished impersonating otherwise your code will keep running with the old identity.
If Kerberos is properly implemented in the domain and your account has permission to impersonate the other account, you can use the WindowsIdentity constructor that only needs a user principal name. That's far safer than storing a username and password in a config file, even it you encrypt them.
A better idea is to clone the data you need (all or just a sample) to a local database and use this during development. This way you will be free to experiment without affecting the production environment (or get blamed for anything untoward).

- 120,703
- 13
- 188
- 236