Run .NET Console Application with logged-in user credentials - c#

I wrote C# based Console Application (with SharePoint Managed Client object model) and configured the credentials in app.config (hard-coded but in encrypted form) to run the application, the application is working fine.
However, now client is having the requirement to run the console application with logged-in user(windows user) credentials and this user will be given admin rights in SharePoint site.
Scenario - If I logged in server where Console application is hosted, then it should run with my credentials without specifying anything in app.config. If another user logged in server, where Console application is hosted, then it should run from his credentials and so on.
Any suggestions ?

I think in the described scenario the behavior should be as fallows:
using (ClientContext context = new ClientContext("[URL]"))
{
Web web = context.Web;
User user = web.CurrentUser; // current logged in user to the server
context.Load(user);
context.ExecuteQuery();
Console.WriteLine(user.LoginName);
}
using (ClientContext context = new ClientContext("[URL]"))
{
context.Credentials = new NetworkCredential("Login", "Password", "domain");
Web web = context.Web;
User user = web.CurrentUser; // user from network credentials
context.Load(user);
context.ExecuteQuery();
Console.WriteLine(user.LoginName);
}

Related

Use Windows Service "Log on as" user as NetworkCredentials for a web request

I developped a windows service that is running Logged On as: a specific windows user.
I use this user, because it has permission for web site I need to request in this windows service.
The issue is that when requesting the web, using CredentialsCache.DefaultNetworkCredentials i uses the credentials of the current user logged in(WindowsIdentity.GetCurrent()) to windows which has no access to this web. I
I need in some way to pass the Credentials of the Windows service's "Log In as" user:
WebRequest request = WebRequest.Create("some url");
// the user running the service can be get from here:
// WindowsIdentity.GetCurrent(), but not the password
request.Credentials = "some code tobtain the user from the service user"
If I use:
request.Credentials = CredentialCache.DefaultNetworkCredentials;
it uses the user from the windows account NOT the windows service account.
Any ideas?
the user running the service can be get from here: WindowsIdentity.GetCurrent(), but not the password
If you can get the current WindowsIdentity, you should be able to impersonate it:
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
using (WindowsImpersonationContext impersonatedUser = currentIdentity.Impersonate())
{
// Check the identity.
Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);
// Make the request
WebRequest request = WebRequest.Create("https://google.com");
// etc
}

How to use Windows User Login to authenticate with Webservice

I have a client-server application (both Windows, client is WPF, non-UWP) and i want to do authentication via active directory. My idea is to take the credentials (or a token) from the windows machine that the client is on and send that information to the server (via webservice, IIS, asp.net). the server then checks with ad if the credentials are valid and does authorization...
So the key points would be:
extract credentials/token from client-windows
send it via vebservice to server (that part should be simple)
validation on server against active directory
How can I achieve that?
If you want to check for a windows user authentication in a desktop application you can simpy use the
Environment.UserName
Variable, it provides the username of the current logged in user.
if you want to check if it is an active directory user you can call a function like this:
public bool UserExists(string username)
{
// create your domain context
using (PrincipalContext domain = new PrincipalContext(ContextType.Domain))
{
// find the user
UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);
return foundUser != null;
}
}
With your new request you can split the code above:
In the client you can get the AD username and domain using Environment variable, pass it to the server and check if the user exist using the UserExist() function

Sharepoint 2010 User Authentication (windows Credential) with Client Object Model

I am trying to login to a SharePoint website that uses Windows Integrated (NTLM) authentication. There are 2 ways to enter credentials for the SharePoint website, Windows Authentication and form authentication.
However, Form authentication is disable on this specific website and I can only use windows authentication. Is there a way for me to login to this site with different credential than what I used to login to my windows machine?
See error here: Form authentication denied
String site = "http://sharepoint/";
ClientContext context = new ClientContext(site);
context.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
FormsAuthenticationLoginInfo formsAuthInfo = new FormsAuthenticationLoginInfo("MyUser", "MyPassword");
context.FormsAuthenticationLoginInfo = formsAuthInfo;
// The SharePoint web at the URL.
Web web = context.Web;
// We want to retrieve the web's properties.
context.Load(web);
// Execute the query to the server.
context.ExecuteQuery();
InitializeComponent();
I also tried to use:
context.Credentials = new NetworkCredential("user", "pass", site);
ClientContext context = new ClientContext(site);
context.Credentials = new NetworkCredential("user", "pass", site);
// The SharePoint web at the URL.
Web web = context.Web;
// We want to retrieve the web's properties.
context.Load(web);
// Execute the query to the server.
context.ExecuteQuery();
InitializeComponent();
I get the following 401 (unauthorized) error
Instead of changing the ClientContext object's AuthenticationMode property to FormsAuthentication, try setting the object's Credentials property to a valid Network Credential object.
ClientContext context = new ClientContext("http://sharepointsite/");
context.Credentials = new NetworkCredential("username","password","domain");
Don't know if it is late but, by default, the managed client object models authenticate users by using their Windows credentials (DefaultCredentials).
So you don't need to explicitly set the Credentials. Just Set following -
context.AuthenticationMode = ClientAuthenticationMode.Default;

LDAP and ActiveDirectory authentication in C#

I am new to LDAP and active directory authentication , I just studied few things about LDAp authentication and done with sample application
I just checking Does the user exist in ActiveDirectory or not
public static bool DoesUserExist()
{
using (var domainContext = new PrincipalContext(ContextType.Domain,Environment.UserDomainName))
{
using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, Environment.UserName))
{
return foundUser != null;
}
}
}
in our local system its working fine , But when i hosted in ActiveDirectory Server and i am trying to access this with server IP address, i am facing some issue like
ContextType.Domain,Environment.UserDomainName and Environment.UserName
for these three values are coming from server Information not the users who accessing this application
So please help me how to get the User information(who accessing this application) so that i need to pass those info to server and need check for user is activedirectory user or not
Environment.UserDomainName returns the domain part of Environment.UserName, e.g. "mydomain.com", so you don't want that.
Environment.UserName itself will return the user who is currently "logged in to Windows", i.e. the app pool user - see MSDN.
You are better off checking the identity of the current web request, so in a MVC Controller or WebForms Page, use this.User.
Or if you are using Windows Authentication or hooking Forms Authentication into AD, the current Thread Principal should be the current request user, so you can use Thread.CurrentPrincipal.Identity.

Unable to connect to my Tfs server from c# code

We're trying to authenticate to our hosted TFS service account in c# using TeamFoundationServer .net control, here is my code :
NetworkCredential tfsCredential = new NetworkCredential(username, password);
TeamFoundationServer tfsServer = new TeamFoundationServer(tfsAddress, tfsCredential);
tfsServer.Authenticate();
Note that this is not an on-premises TFS server, it is the hosted TFS service at tfspreview.com and we try to sign-in with windows live account and with alternate authentication credentials but every time we try to authenticate, internet explorer open in a new windows and ask for credentials.
If we use the IE prompt to connect it works but we want to store the credentials and connect to the server without asking for the credentials every time,
You can either configure basic authentication under your profile or you can use a service credential. It all depends on what sort of permission you need. The basic auth operates under a user account which tends to be bad practice while the service account had elevated permissions.
Configure basic authentication for TF Service
For basic user authentication you should connect to TF Service and open your profile as indicated. There is a "Credentials" tab on your profile which will let you configure those credentials. This is good for per/user access through the API but is not good if you want to run things through a server or service.
Retrieve TFS Service Credentials
I created an application called the TFS Service Credential Viewer that allows you to retrieve the service credentials for your TF Service instance. This is the same thing that the Build & Test servers do when you configure them locally to work against the cloud.
I hope this helps...
You can try with this code based on impersonation of server
var serverUrl = "";
ICredentials credentials = new NetworkCredential(username, password, domain);
ICredentialsProvider TFSProxyCredentials = new NetworkCredentialsProvider(credentials);
TfsTeamProjectCollection currentCollection = new TfsTeamProjectCollection(new Uri(serverUrl), credentials);
// Get the TFS Identity Management Service
IIdentityManagementService identityManagementService = currentCollection.GetService<IIdentityManagementService>();
// Look up the user that we want to impersonate
TeamFoundationIdentity identity = identityManagementService.ReadIdentity(IdentitySearchFactor.AccountName, username, MembershipQuery.None, ReadIdentityOptions.None);
// Open collection impersonated
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(serverUrl), credentials, TFSProxyCredentials, identity.Descriptor);
//For example we can access to service WorkItemStore
var workItemStore = tfs.GetService<WorkItemStore>();
Tfspreview.com now supports basic authentication which would eliminate IE being displayed at all. See here for details on how to set this up for your tfspreview.com and then use the username and password you configured.

Categories

Resources