Connecting to Azure DevOps (TFS) Server with VssConnection and username/password - tfs

Hello trying to connect with my username/password that I use in VS or when logging on web site - but I get this error: VssUnauthorizedException: 'VS30063: You are not authorized to access https://dev.azure.com.'
Or do I have to use a rest oauth token?
var serverUrl = new Uri("https://dev.azure.com/mysite/");
var clientCredentials = new VssBasicCredential(username, password);
var connection = new VssConnection(serverUrl, clientCredentials);
var buildServer = connection.GetClient<BuildHttpClient>();
var sourceControlServer = connection.GetClient<TfvcHttpClient>();
var changesets = buildServer.GetChangesBetweenBuildsAsync("My Project", 1, 1000).Result;

Please try the following code:
var u = new Uri("https://dev.azure.com/mysite");
VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.WindowsCredential(new NetworkCredential("username", "password")));
var connection = new VssConnection(u, c);

As I see you are trying to connect to the azure devops service because your url is https://dev.azure.com/mysite. For TFS we use this template: http://server_name:8080/tfs.
You can not use a user name and password for azure devops service. Use a personal access token and this code:
VssConnection connection = new VssConnection(new Uri("your_url"), new VssBasicCredential(string.Empty, "your_pat"));
Additional information: Authenticating (Azure DevOps Services)

Related

Azure Key Vault Quickstart fails to provide key vault client

I am learning the Azure Key Vault. I am trying to follow https://learn.microsoft.com/en-us/azure/key-vault/secrets/quick-create-net. I have created a vault in the portal, assigned an access policy for a user account. I have seen the vault in the protal, and I have seen that the user has I have set the environment variable value. I use an 'az login' command at a prompt to use that account. From the prompt I run the code in the quickstart. It prompts for a secret. I enter 'bob.' It throws an exception.
"Creating a secret in [...]-key-vault called 'mySecret' with the value 'bob' ...Unhandled exception. Azure.Identity.AuthenticationFailedException: SharedTokenCacheCredential authentication failed: A configuration issue is preventing authentication - check the error message from the server for details.You can modify the configuration in the application registration portal. See https://aka.ms/msal-net-invalid-client for details. Original exception: AADSTS70002: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908."
The exception is at
await client.SetSecretAsync(secretName, secretValue);
I think the problem is coming from
var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
The client is not able to send tokens that the vault accepts. I am at a loss. I have had a couple of people with some expertise in using the Vault review this code and they haven't been able to provide insight. Any help?
Here is the code, from the example:
using System;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
namespace key_vault_console_app
{
class Program
{
static async Task Main(string[] args)
{
const string secretName = "mySecret";
var keyVaultName = Environment.GetEnvironmentVariable("KEY_VAULT_NAME");
var kvUri = $"https://{keyVaultName}.vault.azure.net";
var client = new SecretClient(new Uri(kvUri), new DefaultAzureCredential());
Console.Write("Input the value of your secret > ");
var secretValue = Console.ReadLine();
Console.Write($"Creating a secret in {keyVaultName} called '{secretName}' with the value '{secretValue}' ...");
await client.SetSecretAsync(secretName, secretValue);
Console.WriteLine(" done.");
Console.WriteLine("Forgetting your secret.");
secretValue = string.Empty;
Console.WriteLine($"Your secret is '{secretValue}'.");
Console.WriteLine($"Retrieving your secret from {keyVaultName}.");
var secret = await client.GetSecretAsync(secretName);
Console.WriteLine($"Your secret is '{secret.Value}'.");
Console.Write($"Deleting your secret from {keyVaultName} ...");
DeleteSecretOperation operation = await client.StartDeleteSecretAsync(secretName);
// You only need to wait for completion if you want to purge or recover the secret.
await operation.WaitForCompletionAsync();
Console.WriteLine(" done.");
Console.Write($"Purging your secret from {keyVaultName} ...");
await client.PurgeDeletedSecretAsync(secretName);
Console.WriteLine(" done.");
}
}
}
Not Sure the root reason for it. But If you want to use a user account to login to Azure and access your key vault, using UsernamePasswordCredential() could be a workaround here.
To use UsernamePasswordCredential(), you should register a client application in Azure AD: Go to Azure portal =>Azure Active Directory => New registration
Note its application ID:
Go to API permissioms, and grant key vault user_impersonation permission so that users could access key vault via this app.
Click "Grant admin consent for.." to finish the permission grant process.
Go to the "Authentication" blade, turn on "Allow public client flows" so that Azure will consider this app as a public client:
Try the code below to create a secret:
using System;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
namespace key_vault_console_app
{
class Program
{
static async Task Main(string[] args)
{
const string secretName = "mySecret2";
var keyVaultName = "<your kv name>";
var kvUri = $"https://{keyVaultName}.vault.azure.net";
var userCred = new UsernamePasswordCredential("<user account name>", "<user password>", "<your tenant name/id>", "<client application ID WHCIH we created above>");
var client = new SecretClient(new Uri(kvUri), userCred);
Console.Write("Input the value of your secret > ");
var secretValue = Console.ReadLine();
Console.Write($"Creating a secret in {keyVaultName} called '{secretName}' with the value '{secretValue}' ...");
await client.SetSecretAsync(secretName, secretValue);
Console.WriteLine(" done.");
}
}
}
Result:

Connecting to Azure DevOps and TFS with VssConnection and username/password

I have a service which import tasks from TFS and Azure Devops. I use Microsoft.TeamFoundationServer.Client 16.153.0
I'm trying to connect to TFS using next code
var httpClient = new WorkItemTrackingHttpClient(new Uri(_settings.ServerAddress), new VssBasicCredential(_settings.Login, _settings.Password));
var taskQuery = "..."
var queryResult = await httpClient.QueryByWiqlAsync(tasksQuery, timePrecision:true);
This code works only for first time. If I change login/password and import tasks again it still using previous login/password even if it wrongs. And It doesn't work for azure devops.
What do I wrong?
Try using the following code to connect to DevOps. It obtain the PAT you defined in the code:
Uri uri = new Uri(_uri);
string personalAccessToken = _personalAccessToken;
string project = _project;
VssBasicCredential credentials = new VssBasicCredential("", _personalAccessToken);

Unable to find DiscoveryClient for IdentityServer4

Trying to access discovery client for acceising other endpoints anf following with,
http://docs.identityserver.io/en/aspnetcore1/endpoints/discovery.html
Installed IdentityModel nuget package in .Net 7.5 MVC application. But unable to find the DiscoveryClient.
var discoveryClient = new DiscoveryClient("https://demo.identityserver.io");
var doc = await discoveryClient.GetAsync();
Is there something change in Identitymodel for IdentityServer4
Also, unable to find parameter for "Tokenclient".
Able to figure out, change in IdentityModel, its all extension of HttpClient.
https://identitymodel.readthedocs.io/en/latest/client/discovery.html
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://demo.identityserver.io");
Yes, you are correct. There are lot of changes in the IdentityModel NuGet package.
Below code will help you:
HttpClient httpClient = new HttpClient();
//Below code will give you discovery document response previously we were creating using DiscoveryClient()
// They have created `.GetDiscoveryDocumentAsync()` extension method to get discovery document.
DiscoveryDocumentResponse discoveryDocument = await httpClient.GetDiscoveryDocumentAsync();
// To create a token you can use one of the following methods, which totally depends upon which grant type you are using for token generation.
Task<TokenResponse> RequestAuthorizationCodeTokenAsync(AuthorizationCodeTokenRequest)
Task<TokenResponse> RequestClientCredentialsTokenAsync(ClientCredentialsTokenRequest)
Task<TokenResponse> RequestDeviceTokenAsync(DeviceTokenRequest)
Task<TokenResponse> RequestPasswordTokenAsync(PasswordTokenRequest)
Task<TokenResponse> RequestRefreshTokenAsync(RefreshTokenRequest)
Task<TokenResponse> RequestTokenAsync(TokenRequest)
For example if you want to create a token for password grant type then use below code:
PasswordTokenRequest passwordTokenRequest = new PasswordTokenRequest()
{
Address = discoveryDocument.TokenEndpoint,
ClientId = ClientName,
ClientSecret = ClientSecret,
GrantType = GrantTypes.ResourceOwnerPassword,
Scope = scope,
UserName = userName,
Password = password
};
httpClient.RequestPasswordTokenAsync(passwordTokenRequest);
I hope this will help you!
If you used some sample code and the other answers aren't working, because HttpClient doesn't have GetDiscoveryDocumentAsync
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://localhost:5001");
Update your IdentityModel package, in Visual Studio:
Right click Dependencies -> Manage Nuget Packages -> Updates (select "All" in top right corner)

TF30063: You are not authorized to access {mysite}.visualstudio.com

I developed a simple app to do some custom things for our company view the TFS SDK. I was able to get this working for myself locally, but when I deploy the site to a web server I get a not authorized error:
TF30063: You are not authorized to access xxx
This only works locally for me if I am signed into the Team Project from Visual Studio 2012 and running locally from there. Anyone have thoughts on why I can't get this to work when I deploy to another server? Here is the code... Fails at EnsureAuthenticated() (I have also tried the 'Authenticated()' method).
var netCred = new NetworkCredential("username", "password", "domain");
var basCred = new BasicAuthCredential(netCred);
var tfsCred = new TfsClientCredentials(basCred);
tfsCred.AllowInteractive = false;
tfs = new TfsConfigurationServer(new Uri("https://tfsurl"), tfsCred);
tfs.EnsureAuthenticated();
If you are connecting to a TFS server on your domain then you can use NetworkCredential to authenticate:
Uri uri = new Uri("http://vsalm:8080/tfs");
ICredentials credentials = new NetworkCredential("User", "Password");
using (TfsConfigurationServer server = new TfsConfigurationServer(uri, credentials))
{
server.EnsureAuthenticated();
}
If you are connecting to the hosted Team Foundation Service then you may need to enable alternate credentials.

How to include network credentials in Neo4JClient?

So tipically if you install Neo4j in your development environment, you will have a local hosted version of the Neo4Jserver, which usually you can browse with: localhost:7474/db/data.
Your code is like this:
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();
However, one day you will want to connect to your Cloud-based Neo4J Server (Heroku, Azure, etc.)
Of course, that means you will have to provide Network credentials.
If you only use your bare hands, it could be like this:
var http = (HttpWebRequest)WebRequest.Create(new Uri("http://<<your_REST_query"));
var cred = new NetworkCredential("yourusername", "yourpassword");
http.Credentials = cred;
var response = http.GetResponse();
var stream = response.GetResponseStream();
But how can I include network credentials to connect with Neo4JClient? or is there another option that I don't know?
We support the standard URI syntax for basic authentication credentials:
var client = new GraphClient(new Uri("http://user:pass#localhost:7474/db/data"));
From version 1.1.0.0
var username = "app_username"
var password = "1#mGr#phG0d"
var client = new GraphClient(new Uri("http://localhost:7474/db/data"), username, password);

Resources