Cannot access https://dev.azure.com/<myOrg> Using TFS extended client version 15 - azure-devops

We are migrating some code that used to run against an on premise TFS server but now needs to run against Azure DevOps (previously Team Services). The credentials I'm using have been validated to successfully authenticate to our DevOps organization instance, but running the following code after referencing the
Microsoft.TeamFoundationServer.ExtendedClient
NuGet package always results in TF30063: You are not authorized to access https://dev.azure.com/<myOrg> The code is posted below for authenticating via non-interactive authentication. Do I need to use a different authentication mechanism or different credentials type to get this working?
System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(_userName, DecryptedPassword, _domain);
try
{
// Create TeamFoundationServer object
_teamFoundationCollection = new TfsTeamProjectCollection(_serverUrl, networkCredential);
_teamFoundationCollection.Authenticate();
}
catch (Exception ex)
{
// Not authorized
throw new TeamFoundationServerException(ex.Message, ex.InnerException)
}

Since you want to use .Net Client Libraries, you could refer to the following link:
https://learn.microsoft.com/en-us/azure/devops/integrate/concepts/dotnet-client-libraries?view=azure-devops
Patterns for use:
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
const String c_collectionUri = "https://dev.azure.com/fabrikam";
const String c_projectName = "MyGreatProject";
const String c_repoName = "MyRepo";
// Interactively ask the user for credentials, caching them so the user isn't constantly prompted
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
// Connect to Azure DevOps Services
VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
// Get a GitHttpClient to talk to the Git endpoints
GitHttpClient gitClient = connection.GetClient<GitHttpClient>();
// Get data about a specific repository
var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).Result;

Related

Does build pipeline requires internate connection to run

I am using Onprimise AzureDevOps. I am having intranet within the server but no access to internet.
Does the Use Nugget and Nugget installer requires internet to get it success.
If you look here you will find this code:
async function getLatestMatchVersionInfo(versionSpec: string): Promise<INuGetVersionInfo> {
taskLib.debug('Querying versions list');
let versionsUrl = 'https://dist.nuget.org/tools.json';
let proxyRequestOptions = {
proxy: taskLib.getHttpProxyConfiguration(versionsUrl)
};
let rest: restm.RestClient = new restm.RestClient('vsts-tasks/NuGetToolInstaller', undefined, undefined, proxyRequestOptions);
let nugetVersions: INuGetVersionInfo[] = (await rest.get<INuGetVersionInfo[]>(versionsUrl, GetRestClientOptions())).result;
// x.stage is the string representation of the enum, NuGetReleaseStage.Value = number, NuGetReleaseStage[NuGetReleaseStage.Value] = string, NuGetReleaseStage[x.stage] = number
let releasedVersions: INuGetVersionInfo[] = nugetVersions.filter(x => x.stage.toString() !== NuGetReleaseStage[NuGetReleaseStage.EarlyAccessPreview]);
let versionStringsFromDist: string[] = releasedVersions.map(x => x.version);
let version: string = toolLib.evaluateVersions(versionStringsFromDist, versionSpec);
if (!version)
{
taskLib.error(taskLib.loc("Error_NoVersionWasFoundWhichMatches", versionSpec));
taskLib.error(taskLib.loc("Info_AvailableVersions", releasedVersions.map(x => x.version).join("; ")));
throw new Error(taskLib.loc("Error_NuGetToolInstallerFailer", NUGET_TOOL_NAME));
}
return releasedVersions.find(x => x.version === version);
}
And it basically looks for nuget version if it will not find it on local machine. I assume that all this REST calls will not work without internet. So if you do not want to provide access to internet you should use only those versions installed on agents.
Agree with Krzysztof Madej, I think it is feasible to run build pipeline without internet connection. From the description of NuGet tool installer task we can know :
Acquires a specific version of NuGet from the internet or the tools
cache and adds it to the PATH.
So you need to make sure that the nuget version you need is installed on the local machine.
If you don't use upstream packages from the feed in your DevOps server, then your DevOps server machine could just in intranet network.
However, your build agent machine requires internet access, if you to do something that requires to access internet, such as Use Nuget task.

authentication with Xamarin. Android and Microsoft.Azure.Mobile.Client Microsoft provider error

I had a code that worked unlit few days ago: this is an xamarin.android activity code
[Activity(Label = "AuthSample", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
Button login;
//Mobile Service Client reference
private MobileServiceClient client;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
client = new MobileServiceClient("https://XXXXXXX.azurewebsites.net");
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
login = FindViewById<Button>(Resource.Id.buttonLoginUser);
login.Click += onLoginClick;
}
private async void onLoginClick(object sender, EventArgs e)
{
// Load data only after authentication succeeds.
if (await Authenticate())
{
}
}
// Define a authenticated user.
private MobileServiceUser user;
private async Task<bool> Authenticate()
{
var success = false;
try
{
// Sign in with Microsoft login using a server-managed flow.
user = await client.LoginAsync(this,
MobileServiceAuthenticationProvider.MicrosoftAccount);
CreateAndShowDialog(string.Format("you are now logged in - {0}",
user.UserId), "Logged in!");
success = true;
}
catch (Exception ex)
{
CreateAndShowDialog(ex, "Authentication failed");
}
return success;
}
private void CreateAndShowDialog(Exception exception, String title)
{
CreateAndShowDialog(exception.Message, title);
}
private void CreateAndShowDialog(string message, string title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetMessage(message);
builder.SetTitle(title);
builder.Create().Show();
}
}
i did all the instruction in the tutorial.
the LoginAsync redirect me to the Microsoft login page, i am able to authenticate and after a successful authentication i get this error : "the page cannot be displayed because an internal server error has occured"
i am working with 3.1 azure sdk version
According to your description, I assumed that you could follow the steps below to troubleshoot this issue.
For Node.js backend
You could leverage App Service Editor or kudu for create the iisnode.yml file under root folder (D:\home\site\wwwroot) if not exists. Then add the following settings for enable logging to debug a Node.js web app in azure app service:
loggingEnabled: true
logDirectory: iisnode
Additionally, here is a similar issue about enable node.js logging, you could refer to it. Also, for more details about kudu and app service editor, you could refer to here.
For C# backend
you could edit App_Start\Startup.MobileApp.cs file and configure the IncludeErrorDetailPolicy as follows for capturing the error details:
HttpConfiguration config = new HttpConfiguration();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
For a simple way, you could access https://{your-app-name}.azurewebsites.net/.auth/login/{provider-name} via the browser, then check the detailed error message for locating the specific error.
UPDATE:
Based on your address, I checked your app and found I could log with my Microsoft Account via the browser. Then I checked with your table endpoint and found the follow error:
https://{your-app-name}.azurewebsites.net/tables/todoitem?ZUMO-API-VERSION=2.0.0
message: "An error has occurred.",
exceptionMessage: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)",
exceptionType: "System.Data.SqlClient.SqlException",
As I known, when following the quickstart to create the data store for your backend, downloading the C# backend, then deploy the backend to moible app. At this point, your created connection string via azure portal would not be exposed to your ASP.NET application, and the default connection string would use the localdb, you need to edit the Web.config file before deploying to azure mobile app as follows:
<connectionStrings>
<add name="MS_TableConnectionString" connectionString="Data Source=tcp:{your-sqlserver-name}.database.windows.net,1433;Initial Catalog={db-name};User ID={user-id};Password={password}" providerName="System.Data.SqlClient" />
</connectionStrings>
Or configure the connection string when deploy your app to azure mobile app via VS as follows:
It seems that there was a problem in azure or in Microsoft authentication.
after two days of frustration everything just started to work again!!

python social auth load strategy and authenticate user manually with release 0.1.26

I used python social auth for social authentication in the last 2 months and it was great.
I needed QQ support, hence installed newest git commit (23e4e289ec426732324af106c7c2e24efea34aeb - not part of a release).
until now i used to authenticate the user using the following code:
# setup redirect uri in order to load strategy
uri = redirect_uri = "social:complete"
if uri and not uri.startswith('/'):
uri = reverse(redirect_uri, args=(backend,))
# load the strategy
try:
strategy = load_strategy(
request=request, backend=backend,
redirect_uri=uri, **kwargs
)
strategy = load_strategy(request=bundle.request)
except MissingBackend:
raise ImmediateHttpResponse(HttpNotFound('Backend not found'))
# get the backend for the strategy
backend = strategy.backend
# check backend type and set token accordingly
if isinstance(backend, BaseOAuth1):
token = {
'oauth_token': bundle.data.get('access_token'),
'oauth_token_secret': bundle.data.get('access_token_secret'),
}
elif isinstance(backend, BaseOAuth2):
token = bundle.data.get('access_token')
else:
raise ImmediateHttpResponse(HttpBadRequest('Wrong backend type'))
# authenticate the user
user = strategy.backend.do_auth(token)
which worked fine.
In the latest release this behaviour has changed, and an exception is raised since the "load_strategy" method has changed.
I can't seem to find any documentation on how to do it with the new release.
Any help would be appreciated!
Omri.
The last changes in the repository changed the importance of the strategy, instead of being the main entity to perform the authentication, it's just a helper class to glue the framework with the backends. Try with this snippet to load the strategy and the backend:
from social.apps.django_app.utils import load_strategy, load_backend
strategy = load_strategy(request)
backend = load_backend(strategy, backend, uri)
...
user = backend.do_auth(token)

Google Admin SDK throws bad request java client

I am trying to use the admin SDK using the java client. My requirement is for a server side application to manage the users without the explicit consent of the end user. I have followd the following steps.
I have create a service account is the Google API console.
Added the service account to the third party oauth access section the Google Apps admin console
Added the scopes for user, user.readonly for the same.
Created a super admin to be used as the service account user
I am using the java client as follows:
The same action is working in the api explorer using the service email to authenticate
HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();
GoogleCredential credential=null;
try {
credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("xxx#developer.gserviceaccount.com")
.setServiceAccountScopes(DirectoryScopes.all())
.setServiceAccountPrivateKeyFromP12File(new File("/Users/xxx/Downloads/file-privatekey.p12"))
.setServiceAccountUser("xx#subdomain.domain.com") //Super admin account
.build();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Directory directory = new Directory.Builder(HTTP_TRANSPORT,JSON_FACTORY,credential).setApplicationName("Sync Service").build();
try {
Directory.Users.List list = directory.users().list();
list.setDomain("subdomain.domain.com");
//list.setCustomer("xxx");
Users users = list.execute();
} catch (IOException e) {
e.printStackTrace();
}
I am getting the following error. Not sure why!
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "access_denied"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:269)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:858)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at GappsClient.main(GappsClient.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Process finished with exit code 0
Have you add the client ID of your service account to Manage Third Party OAuth Access in your Cpanel?
I followed #Emily Lam answer and formed service account using old Google API console and i was able to get the expected result. Please let me know if anybody needs detailed steps i followed. Follow OAuth 2.0 client IDs part from below URL https://developers.google.com/console/help/#creatingdeletingprojects

How do I get a token needed for DFS Kerberos authentication?

I'm trying to write a client for consuming DFS (Documentum Foundation Services) and trying to use Kerberos for single sign-on. Both Java and C# sample code (productivity layer) in the documentation gives the following line which gets the Kerberos binary token:
byte[] ticket = ...
I'm not sure how to actually get the binary token, and the "..." doesn't help me. Does anyone know how to get an actual ticket (Kerberos token) using either Java or C#?
Here are the examples given for both Java and C#:
Java: Invoking a service with Kerberos authentication
KerberosTokenHandler handler = new KerberosTokenHandler();
IObjectService service = ServiceFactory
.getInstance().getRemoteService(..., contextRoot, Arrays.asList((Handler) handler));
byte[] ticket = ...;
handler.setBinarySecurityToken(
new KerberosBinarySecurityToken(ticket, KerberosValueType.KERBEROSV5_AP_REQ));
service.create(...)
C#: Invoking a service with Kerberos authentication
KerberosTokenHandler handler = new KerberosTokenHandler();
List<IEndpointBehavior> handlers = new List<IEndpointBehavior>();
handlers.Add(handler);
IObjectService service = ServiceFactory
.Instance.GetRemoteService<IObjectService>(..., contextRoot, handlers);
byte[] ticket = ...;
handler.SetBinarySecurityToken(
new KerberosBinarySecurityToken(ticket, KerberosValueType.GSS_KERBEROSV5_AP_REQ));
service.create(...);
I just figured this out for .NET and would like to share for those who maybe interested. What's needed is WSE3 library. Make sure to configure your DFS service account for Kerberos delegation.
So what need to do is set your KerberosTokenHandler with the Kerberos token. The KerberosBinarySecurityToken comes from WSE3. The code would look something like this:
KerberosTokenHandler kerberosTokenHandler = new KerberosTokenHandler();
String servicePrincipalName = “DFS/example66”; // this is the service principal name for your DFS service account in Active Directory.
using (KerberosClientContext kerberosClientContext = new KerberosClientContext(servicePrincipalName, true, ImpersonationLevel.Delegation))
{
KerberosBinarySecurityToken token = new KerberosBinarySecurityToken(kerberosClientContext.InitializeContext(), KerberosValueType.KERBEROSV5_AP_REQ);
kerberosTokenHandlerandler.SetBinarySecurityToken(token);
}