Trouble accessing youtube API via VPN - youtube

Youtube is not accessible in my region, I use a VPN (cyberghost VPN) and use it to hit youtube APIs, to be specific this is how im requesting (through .NET client library):
below is my sample code
YouTubeRequestSettings settings = new YouTubeRequestSettings(Config.YoutubeApplicationName, Config.YouTubeDeveloperKey, Config.YouTubeConnectionUserName, Config.YouTubeConnectionPassword);
YouTubeRequest request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = "XXXXXXXXXXXXXX";
newVideo.Tags.Add(new MediaCategory("XXXXXXXXXXX", YouTubeNameTable.CategorySchema));
newVideo.Keywords = "xxxxx";
newVideo.Description = "XXXXXXXXXXXXXXXXXXXXXXXX";
newVideo.YouTubeEntry.Private = true;
FormUploadToken token = request.CreateFormUploadToken(newVideo);
i get an email about "suspicious login attempt" which makes sense...since Im now logging in through a different country, but I thought I would be able to whitelist some IPs and get through...CANT find any such option there!!
question 1:
Is there an option in youtube developer account to whitelist an IP (a set of IPs)?
Question 2:
If its not possible, HOW else do I do it ? (one possible solution seems to be generation of "Application specific password" )?

I'd recommend switching to OAuth 2 instead of ClientLogin. Using OAuth 2, you authenticate once in a browser using your Google Account, authorize access, and then you get back a token that can be reused to make API calls without having to login again.
https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2

Related

Azure tableclient in console app using interactive authentication

I'm trying to access Azure Table Storage using the TableClient class, but I want to authenticate using AzureAD credentials via the browser popup.
I have tried 2 approaches and are sure I have things configured correctly in Azure, but I just keep getting
This request is not authorized to perform this operation using this
permission.
Here is test code 1 using MSAL
let app = PublicClientApplicationBuilder.Create("---registered app ID---")
.WithAuthority(AzureCloudInstance.AzurePublic, "---tennant id----" )
.WithDefaultRedirectUri()
.Build()
let! ar = app.AcquireTokenInteractive(["https://storage.azure.com/user_impersonation"]).ExecuteAsync()
let tokenCredential = { new TokenCredential() with
member x.GetTokenAsync(_,_) = task {return AccessToken(ar.AccessToken, ar.ExpiresOn)} |> ValueTask<AccessToken>
member x.GetToken(_,_) = AccessToken(ar.AccessToken, ar.ExpiresOn)}
let tc = new TableClient(Uri("https://--endpoint---.table.core.windows.net/"), "--Table--", tokenCredential)
and test 2 using Azure.Identity
let io = new InteractiveBrowserCredentialOptions(ClientId = "---registered app ID---", RedirectUri = Uri("https://login.microsoftonline.com/common/oauth2/nativeclient"))
let tc = new TableClient(Uri("https://--endpoint---.table.core.windows.net/"), "--Table--", new InteractiveBrowserCredential(io))
I have the app registered in Azure & I have added api permissions for Azure Storage, with Admin consent. My account is a Service Administrator for the tennant so I have full access to the storage account. I have scoured all the docs but just cant see what I'm missing.
To access table data using your Azure AD credentials, your user account should be assigned either Storage Table Data Contributor or Storage Table Data Reader role.
Please assign one of these roles to your user account and re-acquire the token. You should not get the error you are getting then.

Error when querying Microsoft Graph API Shifts: "MS-APP-ACTS-AS header needs to be set for application context requests"

We are trying to query shifts in the Microsoft Graph API using a C# app, now that StaffHub got deprecated , in the past we were getting an Unknown Error which looked like a permissions issue.
In the docs I noticed permissions for Schedule.ReadAll and Schedule.ReadWriteAll so I added them to the application permissions in our App Registration in Azure.
Now when we send the request to https://graph.microsoft.com/beta/teams/{teamid}/schedule we get this error:
Microsoft.Graph.ServiceException: 'Code: Forbidden Message: {"error":{"code":"Forbidden","message":"MS-APP-ACTS-AS header needs to be set for application context requests.","details":[],"innererror":{"code":"MissingUserIdHeaderInAppContext"}}}
The documentation says the Schedule permissions are in private preview, are these required for querying a schedule & shifts, and if so, is it possible to request access to the private preview?
I'm in the same situation. It's possible to request private preview access (we have), but I'm guessing that it's primarily granted to Microsoft partners or at least have a connection at Microsoft.
The workaround for me has been getting access on behalf of a user. It does however require the user to enter username and password in order to get an access token, so it might not be a perfect solution for you. But it works. You need to add (and, I believe, grant admin consent for) delegated permissions for this to work, either Group.Read.All or Group.ReadWrite.All.
Edit:
I've got it working now. We have private preview access, so I'm not sure this will help you unless you do too, but as I understand it will be available eventually. Given your question, I presume you already have an access token.
Add MS-APP-ACT-AS as a header with the user ID of the user you want the Graph client to act as.
If you're using the Graph SDK for .NET Core you can just add a header to the authentication provider:
public IAuthenticationProvider GetAuthenticationProviderForActingAsUser(string userId, string accessToken)
{
return new DelegateAuthenticationProvider(
requestMessage =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// Get event times in the current time zone.
requestMessage.Headers.Add("Prefer", "outlook.timezone=\"" + TimeZoneInfo.Local.Id + "\"");
requestMessage.Headers.Add("MS-APP-ACTS-AS", userId);
return Task.CompletedTask;
});
}
Then you call the graph service client:
var authenticationProvider = GetAuthenticationProviderForActingAsUser(userId, accessToken);
var graphClient = new GraphServiceClient(authenticationProvider);
You should then be able to fetch the shifts:
var shifts = await graphClient.Teams[teamId].Schedule.Shifts
.Request()
.AddAsync(shift);

Error 400: invalid_scope "https://www.googleapis.com/auth/chat.bot"

The documentation for the new google hangouts chat says that you need to authorize the scope https://www.googleapis.com/auth/chat.bot to do pretty much anything.
Here's the error:
While generating an authentication URL using their OAuth2 client I get the message that the scope is invalid. I don't have that problem if I use https://www.googleapis.com/auth/chat or some other scope like the one for google plus.
When I try to google things on in the API Explorer no combination of the URL or parts of the URL work either.
Here is my code to fetch the URL, seems to work just fine for everything else:
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(
"clientid-idididid.apps.googleusercontent.com",
"_secretsuff",
"http://localhost:3000/auth/google/callback"
);
var scopes = [
"https://www.googleapis.com/auth/chat", //Works
"https://www.googleapis.com/auth/chat.bot" // Does not work
];
var url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes,
});
console.log(url);
In case others are running across this problem I think I've figured this out. Google doesn't seem need this auth scope enabled by a domain user because it's already authorised on the domain when your testing your bot. The "authorisation" of these scopes are dictated by users in a domain adding/removing bots from spaces.
I'll go into a bit of detail if you're confused.
When you create a bot in the console for an organisation https://console.cloud.google.com/apis/api/chat.googleapis.com/ your bot is added to the domain and can be added to spaces by users. If then go over to to the credentials and create a service account you can use that json file credentials to access the API as your bot. The code below gets a list of the people in a space.
var { google } = require('googleapis');
var chat = google.chat("v1");
var key = require('./google_service-account-credentials.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
['https://www.googleapis.com/auth/chat.bot'], // an array of auth scopes
null
);
jwtClient.authorize(function (err, tokens) {
chat.spaces.members.list({
auth: jwtClient,
parent: "spaces/AAAAD4xtKcE"
}, function (err, resp) {
console.log(resp.data);
});
});
If you try to get a list of members on other spaces (and other domains) the bot will fail with the exact same error message:
"Bot is not a member of the space."
I assume if you list your bot on the marketplace and it gets added to different domains and spaces google's API makes sure that your bot can do what it's trying to do on a space by space basis. It would be annoying have to setup some authentication flow after a bot has already been added for it to do its job. This is also probably why the current REST api doesn't let you list spaces under domains, it's not the paradigm this API works under.
It may have to do with one of the following:
The scope is created for service accounts. Make sure you are accessing the REST API with a service account.
Make sure that the bot is added to the room or space and has access to what you want it do.
Make sure the Service account is part of the bot project that you are using for the bot.

Configure multiple login sessions using google oauth

I am using Google OAuth for Google signin with Odoo.
Everything works fine and I can sign in using google with no problem. However, I cannot open multiple sessions using my same google credentials.
For example, if I open two sessions, one in chrome and another in firefox, then the older session gets logged out.
I don't understand what's the problem because no matter how many sessions I start if I log in using my username and password separately, without using google OAuth, none of the sessions get logged out - works fine.
I was wondering it has got something to do with the code, so I did a lot of tweaks but nothing works. I saw that at one point it cannot get the session information of older sessions. However my question is not about the code.
My question is, is there any configuration or setting to be set in google OAuth or Odoo 8 which lets users have multiple sessions at the same time or is there any setting while using google OAuth with Odoo that I need to know for this?
Any idea would be really helpful as I've been struggling for days with this. Thanks!
I have build a module for Odoo V9. Without this module, Odoo save only one token. But when you use odoo in multi computer, you use one token for each computer.
By default odoo don't support multi token. You need to modify the code of module auth_oauth.
With this module it save all token, like that you can have multi connection.
You can donwload and instal this module : https://github.com/IguanaYachts/auth_oauth_multi_token.git
class ResUsers(models.Model):
_inherit = 'res.users'
oauth_access_token_ids = fields.One2many('auth.oauth.multi.token', 'user_id', 'Tokens', copy=False)
oauth_access_max_token = fields.Integer('Number of simultaneous connections', default=5, required=True)
#api.model
def _auth_oauth_signin(self, provider, validation, params):
res = super(ResUsers, self)._auth_oauth_signin(provider, validation, params)
oauth_uid = validation['user_id']
user_ids = self.search([('oauth_uid', '=', oauth_uid), ('oauth_provider_id', '=', provider)]).ids
if not user_ids:
raise openerp.exceptions.AccessDenied()
assert len(user_ids) == 1
self.oauth_access_token_ids.create({'user_id': user_ids[0],
'oauth_access_token': params['access_token'],
'active_token': True,
})
return res
#api.multi
def clear_token(self):
for users in self:
for token in users.oauth_access_token_ids:
token.write({
'oauth_access_token': "****************************",
'active_token': False})
#api.model
def check_credentials(self, password):
try:
return super(ResUsers, self).check_credentials(password)
except openerp.exceptions.AccessDenied:
res = self.env['auth.oauth.multi.token'].sudo().search([
('user_id', '=', self.env.uid),
('oauth_access_token', '=', password),
('active_token', '=', True),
])
if not res:
raise
If you follow the steps above you will be able to successfully configure Google Apps (Gmail) with OpenERP via the OAuth module. The only thing i was missing is an extra step I found in a youtube video; you have to:
Go to Settings - Users
To the users you want to give OAuth access, send them a password reset by using the "Send reset password instructions by email" option.
Ask your users (or yourself) to use the link they receive in their email, but, when they open it, they will only see the log in screen with the "Log in with Google" option. (no typical change password option available)
Use the proper Google account and voila! - Now it connects smoothly.
The Youtube video that show how to log in with Google in OpenERP: http://www.youtube.com/watch?v=A-iwzxEeJmc
and if configuration of Oauth2 and odoo see this link for more detail
https://odootricks.wordpress.com/2014/09/18/setting-up-google-apps-authentication-for-odoo/

Error on getting authorization URL more than once in Twitter4j

I'm using Twitter4j to implement the authorization workflow on my webapp (user acesses a page, twitter asks permission, I receive the callback and generate the oauth access token).
My first problem was that if I called a method to get the Twitter sigleton:
Twitter twitter = TwitterFactory.getSingleton();
twitter.setOAuthConsumer(getClientId(), getClientSecret());
1) Since OAuthConsumer would already be defined I would get an exception. And I can't find how to ask the singleton if it already has the credentials defined. What's the best way? My solution was to save the singleton in a private member...
2) Now I want to generate an AuthorizationURL, so I need to ask Twitter singleton the OAuthRequestToken:
RequestToken oauthRequestToken = twitter.getOAuthRequestToken(getCallbackURL()); //FIXME
And this throws an exception:
401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
message - Invalid or expired token.
code - 89
Relevant discussions can be found on the Internet at:
http://www.google.co.jp/search?q=3cc69290 or
http://www.google.co.jp/search?q=45a986a5
TwitterException{exceptionCode=[3cc69290-45a986a5], statusCode=401, message=Invalid or expired token., code=89, retryAfter=-1, rateLimitStatus=null, version=4.0.4}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.post(HttpClientBase.java:86)
at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:115)
at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:92)
at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:292)
at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:287)
(...)
Note: the 'Relevant discussions' links are not working as expected I think...
In short:
1) How can I ask the singleton if it already has the credentials defined in order to 'setOAuthConsumer' doesn't throw an error ?
2) How to re-ask the singleton to generate a new authorizationURL for the user to access and authorize (again) ?
Also posted in the corresponding forum
1) How can I ask the singleton if it already has the credentials defined in order to 'setOAuthConsumer' doesn't throw an error ?
There are a few ways that this can be done. You can set the oAuth consumer key and secret in a properties file named twitter4j.properties on your classpath. When you use the TwitterFactory, this is where the default properties come from.
If you want to set the values programmatically, the TwitterFactory also has a few overloaded constructors which allow this:
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(CONSUMER_KEY);
builder.setOAuthConsumerSecret(CONSUMER_SECRET);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
Twitter twitter = factory.getInstance();
2) How to re-ask the singleton to generate a new authorizationURL for the user to access and authorize (again) ?
I assume that your requirement is to have the user authorize every time. If this is the case, this is handled via Twitters API. There are 2 oAuth endpoints https://api.twitter.com/oauth/authenticate and https://api.twitter.com/oauth/authorize. The authenticate endpoint is the normal Sign in with Twitter functionality where the user will approve once and then automatically logged in every time after. The authorize endpoint will require authorization every time.
Using Twitter4j, these are separate methods that can be called on your RequestToken. You redirect to the appropriate URL based on your requirement.
The solution I've found is presented here:
Twitter instance = new TwitterFactory().getInstance();
instance.setOAuthConsumer(getClientId(), getClientSecret());
RequestToken requestToken = new RequestToken(getOauthToken(),getOauthTokenSecret());
AccessToken oAuthAccessToken = instance.getOAuthAccessToken(requestToken, oauthVerifier);
requestTokenand oauthVerifier are received as parameters in the callback. getOauthToken() and getOauthTokenSecret() retrieve the tokens retrieved by the library in the first step and that were saved in a cache (user -> tokens).
Inspired by this question/answers: Having multiple Twitter instances with twitter4j library.

Resources