I am trying to get the list of users who have access to a project using this Forge API. I have given the scope as account:read. I tried it suing Postman and also from ASP.NET Core backend which I am developing.
In both cases I get the same error:
{
"status": 403,
"type": "",
"id": "80757c600ab0de6c",
"title": "Forbidden",
"detail": "The 3 legged access token does not have access"
}
Is there anything that I need to change in BIM 360 so that I can resolve this error?
This is my backend code (BASE URL):
[HttpPost]
[Route("api/forge/bim360/projectusers")]
public async Task<dynamic> GetProjectUsersAsync([FromQuery] string projectId, [FromQuery] string userId)
{
dynamic access_token = await CheckToken();
RestClient client = new RestClient(BASE_URL);
RestRequest request = new RestRequest("/bim360/admin/v1/projects/{project_id}/users", RestSharp.Method.GET);
request.AddParameter("project_id", projectId, ParameterType.UrlSegment);
request.AddHeader("Authorization", "Bearer " + access_token);
request.AddHeader("User-Id", userId);
try
{
IRestResponse issueTypesResponse = await client.ExecuteGetTaskAsync(request);
dynamic users = JObject.Parse(issueTypesResponse.Content);
return Ok("Found Users");
}
catch (Exception ex)
{
//TODO Add real logger
StreamWriter st = new StreamWriter(#"Logg/logg.txt", true);
st.Write(ex.Message);
st.Close();
return StatusCode(500);
}
}
Any help appreciated.
Just tried your code here and it works just fine.
The error message states that the user on 3LO doesn't have permission to access the project users.
Please note that this endpoint works with 3LO or 2LO (with or without User-id).
If you change to a user with permission or 2LO you should be able to access the project users.
When using 3LO, permission is granted by the user that acquired the token (User-id header is ignored).
Worked on it for some time and figured it out. It has to do with the way the Forge App is setup. The access token that we retrieve can't access user details.
Related
The system administrator enabled 2FA so I'm having to go through and update some programs to utilizes this for accessing the Dynamics API. Otherwise, we received the following:
{
"error":"interaction_required",
"error_description":"AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '00000007-0000-0000-c000-000000000000'.\r\nTrace ID: 24822bc6-9e93-476d-8580-fd04e3889300\r\nCorrelation ID: efd5dbc5-dead-4665-a5a6-570ae15a55fb\r\nTimestamp: 2020-02-24 20:35:15Z",
"error_codes":[
50076
],
"timestamp":"2020-02-24 20:35:15Z",
"trace_id":"24822bc6-9e93-476d-8580-fd04e3889300",
"correlation_id":"efd5dbc5-dead-4665-a5a6-570ae15a55fb",
"error_uri":"https://login.windows.net/error?code=50076",
"suberror":"basic_action"
}
This article makes it sound pretty straight forward and is the process we had to use for Outlook and other apps. Basically, generating an App Password.
However, I'm trying to use the App Password instead of the Default password we've used for a while and still am unable to get an access token for the program to use.
Here is what we've been using:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace CrmQbInvoiceSync
{
class CrmAuthorization
{
// Serialize the JSON response for the access_token
public class AccessToken
{
public string access_token { get; set; }
}
public static async Task<string> GetCrmAccessToken()
{
var values = new Dictionary<string, string>
{
// Connection parameters
{"client_id", ConfigurationManager.AppSettings["clientId"]},
{"client_secret", ConfigurationManager.AppSettings["clientSecret"]},
{"resource", ConfigurationManager.AppSettings["crmOrg"]},
{"username", ConfigurationManager.AppSettings["username"]},
{"password", ConfigurationManager.AppSettings["userPassword"]},
{"grant_type", "password"}
};
// Console.WriteLine(values);
// Convert to x-www-form-urlencoded
var content = new FormUrlEncodedContent(values);
try
{
// Send the x-www-form-urlencoded info to the OAuth2 end point
HttpResponseMessage response = await Services.Client.PostAsync(ConfigurationManager.AppSettings["crmUri"], content);
// Get the body from the response
var responseContent = await response.Content.ReadAsStringAsync();
// Extract out the access token from the response
AccessToken responseBody = JsonConvert.DeserializeObject<AccessToken>(responseContent);
// Test if there is an access token present
if (responseBody.access_token != null)
{
// If there is an access token, take it and use it in
// generating the query
var accessToken = responseBody.access_token;
return accessToken;
}
else
{
var accessToken = "Could not get the access token.";
Services.WriteLogFile(accessToken);
Console.WriteLine(accessToken);
return null;
}
}
catch (Exception e)
{
var error = e;
Services.WriteLogFile(error.ToString());
Console.WriteLine(error);
throw;
}
}
}
}
The {"password", ConfigurationManager.AppSettings["userPassword"]} line is what should be affected so I updated the AppSettings with the new App Password. Get this error, but seems like it should be working given I'm using the App Password:
Formatted JSON Data
{
"error":"invalid_grant",
"error_description":"AADSTS50126: Error validating credentials due to invalid username or password.\r\nTrace ID: 17bf1365-32a0-439e-bd99-9eaf8e3bab00\r\nCorrelation ID: 4d24cac1-dae9-49b7-961f-c7c739f885f4\r\nTimestamp: 2020-02-24 20:33:43Z",
"error_codes":[
50126
],
"timestamp":"2020-02-24 20:33:43Z",
"trace_id":"17bf1365-32a0-439e-bd99-9eaf8e3bab00",
"correlation_id":"4d24cac1-dae9-49b7-961f-c7c739f885f4",
"error_uri":"https://login.windows.net/error?code=50126"
}
Really, not sure if I should be updating something else in the program to accommodate MFA, but articles I've read indicate I should just be generating the App Password and it should be good. Suggestions?
I suggest you use a refresh token to refresh the access token. With refresh token, you can bypass this limitation of MFA.
To get a refresh token, you need to follow Azure AD OAuth2 auth code flow to get a refresh token interactively. And then you can get a new token with the refresh token you got.
Notice that the refresh token should be kept in secret. If it was compromised, you can revoke all refresh tokens of a specific use with PowerShell Revoke-AzureADUserAllRefreshToken
I'm trying to use the Gmail API reading the emails, but I'm running into the problem that I want to do a server-side authentification but with all the examples from google Doc., he always shows me window asking me to add my credentials (Gmail & password).
public static async void CreateService()
{
GoogleCredential credential;
using (var stream = new FileStream(#"key.json", FileMode.Open,
FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(GmailService.Scope.GmailLabels,
GmailService.Scope.GmailModify, GmailService.Scope.GmailMetadata,
GmailService.Scope.GmailReadonly);
}
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Gmail",
});
Console.WriteLine(ListMessages(service, "me", ""));
}
Then I got this code from the documentation of the google api of how to read the messages from a user.
public static List<Message> ListMessages(GmailService service, String userId, String query)
{
List<Message> result = new List<Message>();
UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
request.Q = query;
do
{
try
{
ListMessagesResponse response = request.Execute();
result.AddRange(response.Messages);
request.PageToken = response.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
But when I run it I get this error: An error occurred:
Google.Apis.Requests.RequestError
Bad Request [400]
Errors [
Message[Bad Request] Location[ - ] Reason[failedPrecondition] Domain[global]
]
Answer:
If you want to use a user as the authentication account, then no. This is not possible and you will always get a login window pop-up.
Other Methods:
You can however create and use a service account to impersonate your user and bypass the need for authenticating on run. They require a little extra set up but you can create them in the Google Developer Admin Console.
Code Example:
After creating your service account and giving it the roles and permissions it needs (see links below), you only need to make small edits to your code to use it instead of your regular account. This is an example in Python, but you can find other examples on the managing keys page:
import os
from google.oauth2 import service_account
import googleapiclient.discovery
def create_key(service_account_email):
"""Creates a key for a service account."""
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['YOUR SCOPES HERE'])
# Rememer here that your credentials will need to be downloaded
# for the service account, YOU CAN NOT USE YOUR ACCOUNT'S CREDENTIALS!
service = googleapiclient.discovery.build(
'service', 'version', credentials=credentials)
key = service.projects().serviceAccounts().keys().create(
name='projects/-/serviceAccounts/' + service_account_email, body={}
).execute()
print('Created key: ' + key['name'])
References:
Google Developer Admin Console
Google Cloud - Service Accounts
Understanding Service Accounts
Creating and Managing Service Accounts
Creating and Managing Service Account Keys
Granting Roles to Service Accounts
I'm trying to list my coinbase accounts with the following API https://api.coinbase.com/.
I used the following path GET https://api.coinbase.com/v2/accounts.
I systematically get a reject 'Unauthorized (401) error'
Below some important checks I have done:
My software correctly get ressource which does not require specific authorization level like /v2/time for instance
I have waited 48 hours since my API key creation
I have set all the privileges on all the accounts (BTC wallet, EUR wallet etc)
I manage to view my balance on my trading account https://api.pro.coinbase.com/
Any ideas ?
HttpClient _httpClient
var timeStamp = GetSecondsSinceEpoch();
var signature = ComputeSignature($"{timeStamp}GET/v2/accounts", privateKey);
_httpClient.DefaultRequestHeaders.Add("User-Agent", "MyAppClient");
_httpClient.DefaultRequestHeaders.Add("CB-ACCESS-KEY", publicKey);
_httpClient.DefaultRequestHeaders.Add("CB-ACCESS-SIGN", signature);
_httpClient.DefaultRequestHeaders.Add("CB-ACCESS-TIMESTAMP", timeStamp);
private static string ComputeSignature(string preHashString, string privateKey)
{
try
{
using (var hmac = new HMACSHA256(Convert.FromBase64String(privateKey)))
{
var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(preHashString));
return Convert.ToBase64String(hash);
}
}
catch (Exception)
{
//
}
return string.Empty;
}
var response = await _httpClient.DefaultRequestHeaders.GetAsync(new Uri("https://api.coinbase.com/v2/accounts"));
response.EnsureSuccessStatusCode();
var jsonString = await response.Content.ReadAsStringAsync();
EDIT
In fact for access to GET https://api.coinbase.com/v2/accounts, it seems that we should use OAuth authorization and not API KEY, so it takes the form of :
_httpClient.DefaultRequestHeaders.Authorization
= new AuthenticationHeaderValue("Bearer","MyAccessToken")
Once I have created Oauth access via my Coinbase Main Account, I successfully manage to retrieve my accounts information by using Invoke-WebRequest command but I still get Unauthorized (401) error with the CSharp code equivalent
I have the following function to call users from active directory use graph api.
This function is hit on each keyup of a text box. But i am getting following error
Code: TokenNotFound Message: User not found in token cache. Maybe the
server was restarted.
at the line
var user = await graphClient.Users.Request().GetAsync();
Entire function Below:
public async Task<string> GetUsersJSONAsync(string textValue)
{
// email = email ?? User.Identity.Name ?? User.FindFirst("preferred_username").Value;
var identifier = User.FindFirst(Startup.ObjectIdentifierType)?.Value;
var graphClient = _graphSdkHelper.GetAuthenticatedClient(identifier);
string usersJSON = await GraphService.GetAllUserJson(graphClient, HttpContext, textValue);
return usersJSON;
}
public static async Task<string> GetAllUserJson(GraphServiceClient graphClient, HttpContext httpContext, string textValue)
{
// if (email == null) return JsonConvert.SerializeObject(new { Message = "Email address cannot be null." }, Formatting.Indented);
try
{
// Load user profile.
var user = await graphClient.Users.Request().GetAsync();
return JsonConvert.SerializeObject(user.Where(u => !string.IsNullOrEmpty(u.Surname) && ( u.Surname.ToLower().StartsWith(textValue) || u.Surname.ToUpper().StartsWith(textValue.ToUpper()))), Formatting.Indented);
}
catch (ServiceException e)
{
switch (e.Error.Code)
{
case "Request_ResourceNotFound":
case "ResourceNotFound":
case "ErrorItemNotFound":
//case "itemNotFound":
// return JsonConvert.SerializeObject(new { Message = $"User '{email}' was not found." }, Formatting.Indented);
//case "ErrorInvalidUser":
// return JsonConvert.SerializeObject(new { Message = $"The requested user '{email}' is invalid." }, Formatting.Indented);
case "AuthenticationFailure":
return JsonConvert.SerializeObject(new { e.Error.Message }, Formatting.Indented);
case "TokenNotFound":
await httpContext.ChallengeAsync();
return JsonConvert.SerializeObject(new { e.Error.Message }, Formatting.Indented);
default:
return JsonConvert.SerializeObject(new { Message = "An unknown error has occured." }, Formatting.Indented);
}
}
}
// Gets an access token. First tries to get the access token from the token cache.
// Using password (secret) to authenticate. Production apps should use a certificate.
public async Task<string> GetUserAccessTokenAsync(string userId)
{
_userTokenCache = new SessionTokenCache(userId, _memoryCache).GetCacheInstance();
var cca = new ConfidentialClientApplication(
_appId,
_redirectUri,
_credential,
_userTokenCache,
null);
if (!cca.Users.Any()) throw new ServiceException(new Error
{
Code = "TokenNotFound",
Message = "User not found in token cache. Maybe the server was restarted."
});
try
{
var result = await cca.AcquireTokenSilentAsync(_scopes, cca.Users.First());
return result.AccessToken;
}
// Unable to retrieve the access token silently.
catch (Exception)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.AuthenticationFailure.ToString(),
Message = "Caller needs to authenticate. Unable to retrieve the access token silently."
});
}
}
Can you help whats going wrong?
I know this is 4 months old - is this still an issue for you?
As the previous respondent pointed out, the error you're seeing is being thrown in the catch block in your code meant to handle an empty users collection.
In case you're stuck on this, or anyone else comes here - if you used this sample (or using ConfidentialClientApplication in any respect) and are throwing this exception, it's because your _userTokenCache has no users*. Of course, it's not because your AD has no users, otherwise you wouldn't be able to authenticate. Most likely, it is because a stale cookie in your browser is being passed as the access token to your authProvider. You can use Fiddler (or just check your localhost browser cookies) to find it (should be called AspNetCore.Cookies, but you may want to clear all of them).
If you're storing the tokencache in session (as the example is), remember that each time you start and stop the application, your working memory will be thrown out so the token provided by your browser will no longer match the new one your application will retrieve upon starting up again (unless, again, you've cleared the browser cookies).
*cca.Users is no longer used or supported by MSAL - you have to use cca.GetAccountsAsync(). If you have a deployed application running with the deprecated IUser implementation, you'll have to change this. Otherwise, in development your compiler will complain and not let you build, so you'll already know about this.
Looking at the code, it seems some chunks of logic are missing. For example, you got the method
public async Task<string> GetUserAccessTokenAsync(string userId)
but I can't see where this is being called. Besides that, I don't see the code for fetching a token from Azure AD either. Lastly, the error message you mention
Code: TokenNotFound Message: User not found in token cache. Maybe the server was restarted.
Seems like the error you're throwing
if (!cca.Users.Any()) throw new ServiceException(new Error
{
Code = "TokenNotFound",
Message = "User not found in token cache. Maybe the server was restarted."
});
Since the code isn't complete, I will try and make an assumption on what might be going wrong.
Firstly, assuming you're using MSAL.Net, a step in the acquisition of a token is missing.
The general flow is (Using GetTokenByAuthorizationCodeAsync())
Client challenges the user
User gets redirected and logs in
Callback is called and the client receives a code from the login process
Pass the code to GetTokenByAuthorizationCodeAsync() to obtain an id_token and depending on the permissions an access token.
GetTokenByAuthorizationCodeAsync() will store the token in the cache
that has been provided to the ConfidentialClientApplication
Retrieve the token from the cache with AcquireTokenSilentAsync()
If we fail to retrieve a token from the cache with AcquireTokenSilentAsync(), we'll request a new one from via
AcquireTokenAsync()
Most of this flow seems to be in place in your code, but it could be you're missing the actual token acquisition. Since no token is retrieved, no user is added to the ConfidentialClientApplication, which means cca.Users.Any() returns false, resulting in an ServiceError
Assuming the whole flow is in place, and you're actually acquiring a token, my second assumption would be that the _memoryCache are different. The _memoryCache in which you saved your token differs from the one you use to acquire a token silently.
I would recommend reading the documentation on token acquisition to determine the type of retrieving is the right fit for your application.
EDIT
Actually, I assume your code is inspired by this example.
What's especially interesting is this part
public GraphServiceClient GetAuthenticatedClient(string userId)
{
_graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
async requestMessage =>
{
// Passing tenant ID to the sample auth provider to use as a cache key
var accessToken = await _authProvider.GetUserAccessTokenAsync(userId);
...
}
return _graphClient;
}
What seems to be happening is that calling var user = await graphClient.Users.Request().GetAsync(); invokes the delegate that is provided to the GraphServiceClient. This in turn calls _authProvider.GetUserAccessTokenAsync(userId); which brings us to the public async Task<string> GetUserAccessTokenAsync(string userId) method. Our error most likely originates here, due to no Users being present in the ConfidentialClientApplication.Users collection
Hope this helps!
I am trying to broadcast live from my .Net application using Youtube.Data.Api v3.
I have set up OAuth and downloaded the .JSON file, and that works fine. I know that, because I have already successfully obtained a list of channels resp. videos on my account, i.e., following code works:
var channelsRequest = ytService.Channels.List("contentDetails, snippet");
channelsRequest.Mine = true;
var channelsListResponse = channelsRequest.Execute();
But if I try to execute a insert request (for completeness I show you the whole method),
public static LiveBroadcast CreateImmediateBroadcast(string title = "DefaultBroadcast") {
var snippet = new LiveBroadcastSnippet();
snippet.Title = title;
snippet.ScheduledStartTime = DateTime.Now;
snippet.ScheduledEndTime = DateTime.Now + TimeSpan.FromMinutes(60);
var status = new LiveBroadcastStatus();
status.PrivacyStatus = "unlisted";
var broadcast = new LiveBroadcast();
broadcast.Kind = "youtube#liveBroadcast";
broadcast.Snippet = snippet;
broadcast.Status = status;
var insertBroadcastRequest = ytService.LiveBroadcasts.Insert(broadcast, "snippet, status");
insertBroadcastRequest.Execute();
return broadcast;
}
I get an exception when calling insertBroadcastRequest.Execute(), namely:
Google.GoogleApiException was unhandled
HResult=-2146233088
Message=Google.Apis.Requests.RequestError
Insufficient Permission [403]
Errors [
Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
]
ServiceName=youtube
Source=Google.Apis
StackTrace:
at Google.Apis.Requests.ClientServiceRequest`1.Execute() in C:\Users\cloudsharp\Documents\GitHub\google-api-dotnet-client\Src\Support\GoogleApis\Apis\Requests\ClientServiceRequest.cs:line 96
at YoutubeConsole.YouTubeAPI.CreateImmediateStream(String title) in C:\Users\bussg\Source\Workspaces\OwnExperimental\YoutubeConsole\YoutubeConsole\YouTubeAPI.cs:line 87
at YoutubeConsole.YouTubeAPI.Test() in
...
Also, for completeness, here is my authorization,
using (var stream = new FileStream(Directory.GetCurrentDirectory() + #"\GoogleAuthOtherApplication.json", FileMode.Open, FileAccess.Read)) {
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.YoutubeForceSsl},
"user",
CancellationToken.None,
new FileDataStore("YouTubeAPI")
).Result;
}
Also, For the YouTubeService.Scope I have tried all options. The insert method should work with ForceSsl according to the documentation.
Also this documentation page sais
Note: A channel must be approved to use the YouTube Live feature, which enables the channel owner to stream live content to that channel. If you send API requests on behalf of an authenticated user whose channel is not enabled or eligible to stream live content, the API will return an insufficientPermissions error.
But all my channels are approved for Youtube Live. Any ideas how to get this to work?
Ok after some testing between us over Email.
You need to have the correct scope "YouTubeService.Scope.YoutubeForceSsl" by changing "user" we forced it to request permissions again. My tutorial on how filedata store works in the Google .net client library
remove the space "snippet, status" by sending "snippet,status" it worked for me.
For the fun of it: Issue 8568:LiveBroadcasts: insert - spaces in part