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

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.

Related

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);

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

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)

To retrieve access token

I have created a MVC application to escalate work to other person inside my organization. I have added all the members in my organization to AAD,
and registered an application there, created app service and linked that app service to registered app with SSO enabled.
Now every time someone visits the app, they can login successfully using their respective credential.
What I want to do know is to retrieve all the members in my AAD and display them inside dropdown list so that anyone can escalate to others by just looking in the dropdown list.
I have tried with sample graph SDK to get the name of users in my organization
with this code
private string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
private string appId = ConfigurationManager.AppSettings["ida:AppId"];
private string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"];
private string scopes = ConfigurationManager.AppSettings["ida:GraphScopes"];
public async Task<string> GetUserAccessTokenAsync()
{
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
HttpContextWrapper httpContext = new HttpContextWrapper(HttpContext.Current);
TokenCache userTokenCache = new SessionTokenCache(signedInUserID, httpContext).GetMsalCacheInstance();
//var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache
ConfidentialClientApplication cca = new ConfidentialClientApplication(
appId,
redirectUri,
new ClientCredential(appSecret),
userTokenCache,
null);
try
{
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }), cca.Users.First());
return result.AccessToken;
}
// Unable to retrieve the access token silently.
catch (Exception)
{
HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties() { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
throw new ServiceException(
new Error
{
Code = GraphErrorCode.AuthenticationFailure.ToString(),
Message = Resource.Error_AuthChallengeNeeded,
});
}
}
with some change in scope.
<add key="ida:AppId" value="xxxxx-xxxxxxx-xxxxxx-xxxxxxx"/>
<add key="ida:AppSecret" value="xxxxxxxxxxx"/>
<add key="ida:RedirectUri" value="http://localhost:55065/"/>
<add key="ida:GraphScopes" value="User.ReadBasic.All User.Read Mail.Send Files.ReadWrite"/>
This enables me to get basic details of all user in my organization.
But how I can achieve this in my app where authentication related stuffs are done in azure only, and there is no code for authentication and authorization in entire solution.
Thanks
Subham, NATHCORP, INDIA
But how I can achieve this in my app where authentication related stuffs are done in azure only, and there is no code for authentication and authorization in entire solution.
Based on my understanding, you are using the build-in feature App Service Authentication / Authorization. You could follow here to configure your web app to use AAD login. And you need to configure the required permissions for your AD app as follows:
Note: For Azure AD graph, you need to set the relevant permissions for the Windows Azure Active Directory API. For Microsoft Graph, you need to configure the Microsoft Graph API.
Then, you need to configure additional settings for your web app. You could access https://resources.azure.com/, choose your web app and update App Service Auth Configuration as follows:
Note: For using Microsoft Graph API, you need to set the resource to https://graph.microsoft.com. Details, you could follow here.
For retrieving the access token in your application, you could get it from the request header X-MS-TOKEN-AAD-ACCESS-TOKEN. Details, you could follow Working with user identities in your application.
Moreover, you could use Microsoft.Azure.ActiveDirectory.GraphClient package for Microsoft Azure Active Directory Graph API, Microsoft.Graph package for Microsoft Graph API using the related access token.

User.Identity.Name is different before and after publishing to Azure

I am using #User.Identity.Name in my Asp.net mvc web application. This is shown as Domain\user on local and user#domain.com on azure site once deployed. Instead of using #User.Identity.Name, is there any way to make it unique on local and server. I have many code breaking areas due to this conflict.
I added Azure active directory authentication to my application which is hosted on Azure.
using (var context = new PrincipalContext(ContextType.Domain))
{
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
var displayName = principal?.DisplayName;
}
this displayName is shown on local and once published to Azure it is like null "". What would be the best way to show display name on Azure server once published?
It seems you are using the AD libraries for traditional on-premise AD. To program against Azure AD , you could use OpenID Connect to authenticate users from an Azure AD tenant. Please see the code sample below :
https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect
To get the display name of the current user , you could try :
var displayName = ((System.Security.Claims.ClaimsIdentity)User.Identity).Claims.Where(c => c.Type == "name").FirstOrDefault().Value;
If you also want to show Domain\DisplayName when using Azure AD , you could get domain name by :
var domian= ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value.Split('#')[1].ToString();

Get Error (error=access_denied) while logging in MVC5 application with facebook SDK

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.

Resources