I'm having trouble authenticating as a specific user on MS Team Foundation Server. In older versions it would look like:
teamFoundationCredential = new System.Net.NetworkCredential("<USERNAME>", "<PASSWORD>", "<DOMAIN>");
TeamFoundationServer tfs = new TeamFoundationServer("http://mars:8080/", teamFoundationCredential);
Can some one tell me the equivilent for the 2010 version. So far I have:
ICredentialsProvider cred = null;
tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://asebeast.cpsc.ucalgar.ca:8080/tfs/DefualtCollection"));
tfs.EnsureAuthenticated();
Thanks
For TFS 2010, use the following:
TfsTeamProjectCollection collection = new TfsTeamProjectCollection(
new Uri("http://asebeast.cpsc.ucalgar.ca:8080/tfs/DefaultCollection",
new System.Net.NetworkCredential("domain_name\\user_name", "pwd"));
collection.EnsureAuthenticated();
I've been having the same problem. The above solution doesn't work for me and really can't figure out why. I keep getting a cast exception.
Spent a day trying to figure this out - so thought I'd share my current workaround to the problem.
I've created my own internal class that implements ICredentialsProvider - as below:
private class MyCredentials : ICredentialsProvider
{
private NetworkCredential credentials;
#region ICredentialsProvider Members
public MyCredentials(string user, string domain, string password)
{
credentials = new NetworkCredential(user, password, domain);
}
public ICredentials GetCredentials(Uri uri, ICredentials failedCredentials)
{
return credentials;
}
public void NotifyCredentialsAuthenticated(Uri uri)
{
throw new NotImplementedException();
}
#endregion
}
I then instantiate this and pass it in as below:
MyCredentials credentials = new MyCredentials(UserName, Password, Domain);
TfsTeamProjectCollection configurationServer =
TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
new Uri(tfsUri), credentials);
Note that I haven't implemented the NotifyCredentialsAuthenticated - not sure what this actually does, so left the NotImplementedException in there so I could catch when its called, which so far hasn't happened. Now successfully connected to TFS.
I've had some problems connecting to our old TFS 2008 server using this method as well, but the thing that solved my case was really simple:
First I defined the TFS Url to be:
private const string Tfs2008Url = #"http://servername:8080/tfs/";
static readonly Uri Tfs2008Uri = new Uri(Tfs2008Url);
The path used in the URL is the one we use when connecting via VisualStudio, so I thought this had to be the same in API calls, but when I tried to use this with the following authentication, I got a TF31002 / 404 error:
var collection = new TfsTeamProjectCollection(Tfs2008Uri,new NetworkCredential("AdminUser","password","domain_name"));
collection.EnsureAuthenticated();
But when I changed the Url to the TFS root, it authenticated OK!
private const string Tfs2008Url = #"http://servername:8080/";
static readonly Uri Tfs2008Uri = new Uri(Tfs2008Url);
Don't know if that helped anyone, but it sure did the trick for me!
This has worked pretty good for me:
_tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUri);
_tfs.ClientCredentials = new TfsClientCredentials(new WindowsCredential(new NetworkCredential("myUserName", "qwerty_pwd", "myDomainName")));
_tfs.EnsureAuthenticated();
Related
I am using OAuth2.0 to connect to Exchange webservices. Everything else seems to work ok for me . However when i try to subscribe one of the room resource by using grouping info and providing the anchor mailbox as one of the primary mail box it throws an error.
"Request failed because EWS could not contact the appropriate CAS server for this request."
So for example i am trying to subscribe nitroom1 and one the primary mailbox associated with the group is nitroom2 which i am using as X-AnchorMailbox then i got the above error.
public static ExchangeService GetExchangeService(string exchangeURL, string userName, string password, string resourceEmail, string primaryMailbox, string clientID, string tenantID, string clientSecret, string certName)
{
ExchangeService service;
service = new ExchangeService(setTZtoUTC);
service.Url = new Uri(exchangeURL);
if (!string.IsNullOrWhiteSpace(clientID) && !string.IsNullOrWhiteSpace(tenantID))
{
string oAuthToken = multiExchangeManager.getOAuthTokenFromCache(clientID, tenantID, clientSecret, certName);
service.Credentials = new OAuthCredentials(oAuthToken);
}
else
{
service.Credentials = new WebCredentials(userName, password);
}
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, resourceEmail);
service.HttpHeaders.Add("X-AnchorMailbox", primaryMailbox);
service.HttpHeaders.Add("X-PreferServerAffinity", "true");
return service;
}
However if i connect ews using impersonate account then do same thing it works fine.
Also, if i use resourceMailbox same as primary mailbox then it works ok as well.so in my example it will look like this.
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "nitroom1");
service.HttpHeaders.Add("X-AnchorMailbox", "nitroom1");
This is how i am trying to use subscription.
exchangeService.SubscribeToStreamingNotifications(
new FolderId[] { WellKnownFolderName.Calendar, WellKnownFolderName.DeletedItems },
EventType.Created, EventType.Deleted, EventType.Modified, EventType.Moved, EventType.Copied);
Does anyone have any idea why its happening or what i am doing wrong here?
one more thing to add, i tried EWSEditor tool which provides subscription info and both above mentioned resources sharing same grouping info.
I think i found a solution for this issue, i just need to set
X-BackEndOverRideCookie with any service used for subscribing child mailbox.
For more info read this article
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-maintain-affinity-between-group-of-subscriptions-and-mailbox-server
I'm using the .NET libraries for accessing Visual Studio Team Services and i'm trying to work around a glaring design flaw on Microsoft's part. Apparently you can't have more than one collection per server/account, so i have to use several accounts, which in this example i'll refer to as collections, since Microsoft has even made clear they map to the same thing.
What i'm actually trying to achieve is to have a list with all my work items from all the collections i'm a member of. I have a QueryWorkItems() method that uses GetAllCollections() to get all my collections. That method has been tested and it works, it does return the two accounts i have. The top level method that triggers the whole thing is AssignedWorkItems(). My code is as follows:
public static List<TfsTeamProjectCollection> GetAllCollections()
{
// Get collections/accounts associated with user
string request = "https://app.vssps.visualstudio.com/_apis/Accounts?memberId=" + versionControl.AuthorizedIdentity.TeamFoundationId + "&api-version=3.2-preview";
string content = MakeRequestToAPI(request).Result;
dynamic results = JsonConvert.DeserializeObject<dynamic>(content);
List<TfsTeamProjectCollection> collections = new List<TfsTeamProjectCollection>();
// Iterate through all collections
Parallel.ForEach((IEnumerable<dynamic>)results.value, collection =>
{
TfsTeamProjectCollection col = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri((string)collection.accountUri));
collections.Add(col);
});
return collections;
}
public static List<WorkItem> QueryWorkItems(string query)
{
List<WorkItem> workItems = new List<WorkItem>();
List<TfsTeamProjectCollection> collections = GetAllCollections();
//Parallel.ForEach(collections, collection =>
foreach(var collection in collections)
{
WorkItemCollection items = collection.GetService<WorkItemStore>().Query(query);
// Add each work item to the overall list
Parallel.For(0, items.Count, i =>
{
Console.WriteLine(items[i].Title);
lock (workItems)
{
workItems.Add(items[i]);
}
});
}
return workItems;
}
public static List<WorkItem> AssignedWorkItems()
{
Init(); //initializes variables like projectName, workItemStore and VersionControlServer(versionControl)
string myItems = "select * from issue where [System.AssignedTo]=#me";
return QueryWorkItems(myItems);
}
When i call the AssignedWorkItems method i get a login prompt, even though i have a default connection already setup:
After i input my credentials though, in this line:
WorkItemCollection items = collection.GetService().Query(query);
i get the following error:
An unhandled exception of type 'Microsoft.TeamFoundation.TeamFoundationServiceUnavailableException'
occurred in Microsoft.TeamFoundation.Client.dll
Additional information: TF31002: Unable to connect to this Team
Foundation Server: https://xxxxxx.vssps.visualstudio.com/.
Team Foundation Server Url: https://xxxxxx.vssps.visualstudio.com/
Possible reasons for failure include:
The name, port number, or protocol for the Team Foundation Server is incorrect.
The Team Foundation Server is offline.
The password has expired or is incorrect.
Funny thing is everytime i run this the URL mentioned in the error switches back and forth between the two collections i have. Any idea as to why this is happening?
I can test the method QueryWorkItems successfully.
Based on the error message you got, it seems the VSTS URL stored in collections as the format https://account.vssps.visualstudio.com instead of https://account.visualstudio.com. So please confirm the URLs stored in collections for the method GetAllCollections are correct.
I used this GetAllCollections method to verify QueryWorkItems:
public static List<TfsTeamProjectCollection> GetAllCollections()
{
List<TfsTeamProjectCollection> collections = new List<TfsTeamProjectCollection>();
NetworkCredential cred1 = new NetworkCredential("username for Alternate authentication", "password for Alternate authentication");
TfsTeamProjectCollection tpc1 = new TfsTeamProjectCollection(new Uri("https://account1.visualstudio.com"), cred1);
collections.Add(tpc1);
NetworkCredential cred2 = new NetworkCredential("username for Alternate authentication", "password for Alternate authentication");
TfsTeamProjectCollection tpc2 = new TfsTeamProjectCollection(new Uri("https://account2.visualstudio.com"), cred2);
collections.Add(tpc2);
return collections;
}
I'm trying to use the library "libgit2sharp" to clone a repository via a SSH key and... I can't find anything... I can clone it via "https" but what I'd like to do is using an SSH key. It's really unclear if it is supported or not.
As of now, there is a SSH implementation using libssh2 library. You can find it here LibGit2Sharp - SSH
You should add libgit2sharp-ssh dependency on you Project to be able to use it. It is available as a nugget: https://www.nuget.org/packages/LibGit2Sharp-SSH
Disclaimer: I haven't found a formal usage guide yet, what I know is from putting together bits and pieces from other user questions through LibGit2 forums.
From what I understood, you would need to create a new credential using eitherSshUserKeyCredentials OR SshAgentCredentials to authenticate using SSH, and pass it as part of CloneOptions.
In the sample code I use "git" as user, simply because the remote would be something like git#bitbucket.org:project/reponame.git , in which case "git" is the correct user, otherwise you will get an error saying
$exception {"username does not match previous request"}LibGit2Sharp.LibGit2SharpException
The code to clone a repo with SSH should be something like that:
public CloneOptions cloningSSHAuthentication(string username, string path_to_public_key_file, string path_to_private_key_file)
{
CloneOptions options = new CloneOptions();
SshUserKeyCredentials credentials = new SshUserKeyCredentials();
credentials.Username = username;
credentials.PublicKey = path_to_public_key_file;
credentials.PrivateKey = path_to_private_key_file;
credentials.Passphrase = "ssh_key_password";
options.CredentialsProvider = new LibGit2Sharp.Handlers.CredentialsHandler((url, usernameFromUrl, types) => credentials) ;
return options;
}
public CloneOptions cloneSSHAgent(string username){
CloneOptions options = new CloneOptions();
SshAgentCredentials credentials = new SshAgentCredentials();
credentials.Username = username;
var handler = new LibGit2Sharp.Handlers.CredentialsHandler((url, usernameFromUrl, types) => credentials);
options.CredentialsProvider = handler;
return options;
}
public void CloneRepo(string remotePath, string localPath){
CloneOptions options = cloningSSHAuthentication("git", "C:\\folder\\id_rsa.pub", "C:\\folder\\id_rsa");
Repository.Clone(remotePath, localPath, options);
}
I have developed an application with ASP.NET MVC5. I have used Facebook external authentication in my application.
When I debug this application with the "Locallhost" domain, the Facebook login works well but when I publish the application in the main server,the AuthenticationManager.GetExternalLoginInfo() returns null and it gives me an error like this in the url:
http://xxxxx.com/Account/ExternalLoginCallback?ReturnUrl=%2Fen&error=access_denied#_=_
I have set the "Site URL" as "http://xxxx.com" and "Valid OAuth redirect URIs" as "http://xxxx.com/signin-facebook" in the Facebook development console.
My setting in the Startup.Outh.cs file is:
var FacebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions();
FacebookOptions.AppId = ConfigurationManager.AppSettings["Facebook_User_Key"];
FacebookOptions.AppSecret = ConfigurationManager.AppSettings["Facebook_Secret_Key"];
FacebookOptions.Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider()
{
OnAuthenticated = async context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
foreach (var claim in context.User)
{
var claimType = string.Format("urn:facebook:{0}", claim.Key);
string claimValue = claim.Value.ToString();
if (!context.Identity.HasClaim(claimType, claimValue))
context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
}
}
};
FacebookOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
app.UseFacebookAuthentication(FacebookOptions);
I don't know why the external login does not work only in the server with my main domain name. please help me about this problem.
I encountered pretty much the same symptoms you describe:
shortly:
A Facebook authentication worked well on localhost, and after uploading the project to another server (and changing the site URL on Facebook console), authentication did not succeed.
I would recommend you roll back to the MVC template code, and if that works - notice any changes you have made to the middleware code (Startup.Auth.sc).
In particular pay attention to code that interacts with LOCAL configuration, such as Disk I/O and OS permissions for local services.
My particular case:
Starting from the Owin/Katana supported Visual Studio template of a WebAPI project, external login was working perfectly with Facebook, Microsoft and Google OAuth middleware, when testing on localhost.
Later I added come code to Startup.Auth.sc because I needed further authentication activity.
So this was the original code:
public void ConfigureAuth(IAppBuilder app)
{
// see WebAPI template of Visual Studio 2013/2015
...
app.UseFacebookAuthentication(
appId: 99999999,
appSecret: *******);
}
and this was replacement:
public void ConfigureAuth(IAppBuilder app)
{
// see WebAPI template of Visual Studio 2013/2015
...
app.UseFacebookAuthentication(GetFacebookAuth());
}
private FacebookAuthenticationOptions GetFacebookAuth()
{
string picRequest =
String.Format("/me/picture?redirect=false&width={0}&height={0}", ProfileInfoClaimsModel.PIC_SIDE_PX);
var facebookProvider = new FacebookAuthenticationProvider()
{
OnAuthenticated = async (context) =>
{
var client = new FacebookClient(context.AccessToken);
dynamic me = client.Get("/me?fields=id,name,locale");
dynamic mePicture = client.Get(picRequest);
// storing temporary social profile info TO A LOCAL FOLDER
// uploading the local folder to a service WITH A LOCAL CREDENTIAL FILE
...
}
};
var options = new FacebookAuthenticationOptions()
{
AppId = 0123456789,
AppSecret = ******,
Provider = facebookProvider,
};
return options;
}
You may notice that my comments will make the problem obvious - the code points to local resources.
Then I published the project to a virtual server (by Amazon EC2) running Windows Server 2012 with IIS 8.5.
From that moment I kept getting error=access_denied in the redirect from /signin-facebook.
I decided to follow this good old concept, and go back to the original template code. Pretty soon I figured out that I forgot to configure the new server. For instance, the folder the code refers to did not exist and the site had no permission to create it.
Obviously, that solved it.
I've tried two ways of connecting to the workitemstore for the TFS server we're running. Attempt A was to connect to the configuration server and use GetService<WorkItemStore>() method. This always returns null.
Attempt B was to connect to the TfsTeamProjectCollection and use the GetService<WorkItemStore>() method or pass the project collection into the WorkItemStore constructor. On attempt B, I get an exception stating "Error HRESULT E_FAIL has been returned from a call to a COM component." The only info I can find on that seems to indicate some permissions problem, but I've confirmed I'm authenticated as a user with read access to the whole project collection and I connect and meddle appropriately via VS 2011 dev preview.
Here's how I'm connecting...
public TfsConfigurationServer GetConfigurationServer()
{
Uri tfsUri = new Uri(configs.TfsUri);
TfsConfigurationServer server = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri, credProvider);
server.Authenticate();
if (server.HasAuthenticated == false)
throw new InvalidOperationException("You can't authenticate against the tfs instance.");
return server;
}
public TfsTeamProjectCollection GetProjectCollectionInstance(string projectCollectionName)
{
Uri tfsUri = new Uri(configs.TfsUri + "/" + projectCollectionName);
TfsTeamProjectCollection collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(tfsUri, credProvider);
collection.Authenticate();
if (collection.HasAuthenticated == false)
throw new InvalidOperationException("You can't authenticate against the tfs instance.");
return collection;
}
and here's how I'm trying to get the WorkItemStore (silly code to illustrate the problem)...
public WorkItemProvider()
{
if (workItems == null)
workItems = ServerProvider.ServerInstance.GetService<WorkItemStore>();
if (workItems == null)
workItems = ServerProvider.ProjectCollectionInstance.GetService<WorkItemStore>();
if (workItems == null)
workItems = new WorkItemStore(ServerProvider.ProjectCollectionInstance);
if (workItems == null)
throw new NullReferenceException("Couldn't load work item store.");
}
I'm not on the same domain as the server, but I'm authenticating as a domain user with an ICredentialsProvider and I've confirmed I'm authenticated as that user. Any pointers would be helpful.
Check if this does what you need:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
namespace GetsWorkItem
{
class Program
{
static void Main()
{
TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://<TFS>:8080/tfs/<COLLECTION>"));
WorkItemStore workItemStore= (WorkItemStore) teamProjectCollection.GetService(typeof (WorkItemStore));
WorkItem workItem = workItemStore.GetWorkItem(1234);
}
}
}
I believe this article might be able to answer your question. It says that if you instantiate your WorkItemStore in a slightly different way, you'll get a different exception:
System.TypeInitializationException: The type initializer for ‘Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore’ threw an exception. —> System.IO.FileLoadException: Mixed mode assembly is built against version ‘v2.0.50727′ of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
The fix is a simple web.config change, by adding the following:
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
Hope this helps! Worked for me when I was getting the same error.