401 Client Error: Unauthorized for url - python

Recently I started to get
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.soundcloud.com/oauth2/token
using soundcloud (0.5.0) Python library.
It happens in
client = soundcloud.Client(client_id='id',
client_secret='secret',
username='user#mail.com',
password='passwd')
I double checked my credentials to make sure they are not the cause. I tried to get a Client instance from different IPs and different machines. At some random times during a day I can get a Client instance, but 99.99% of the day I get the error.
Does the error mean I was banned for some reason?

It may be helpful, I solved a similar problem by reading the username and password from the configuration file.
Try:
# config.ini
[my_app]
CLIENT_ID = enter_your_id
CLIENT_SECRET = enter_your_secret
USERNAME = enter_username
PASSWORD = enter_password
Install configparser from Python 3.8 for Python 2.6+: pip install configparser.
See the great documentation for more details.
import configparser
config = configparser.RawConfigParser()
config.read('config.ini')
my_id = config.get('my_app', 'CLIENT_ID')
my_secret = config.get('my_app', 'CLIENT_SECRET')
my_user = config.get('my_app', 'USERNAME')
my_pass = config.get('my_app', 'PASSWORD')
client = soundcloud.Client(client_id=my_id,
client_secret=my_secret,
username=my_user,
password=my_pass)

Probably you are using a third-party app to access your account,
in case you are using Gmail service for your purpose, consider allowing third-party apps to have access to your Gmail account, how are you going to do that:
Go to https://myaccount.google.com/security
Use Two-Step-Authentication and enable it.
Create an App Password, Select App > Mail | Select Device > Windows Computer.
And use the password given
And that should solve your issue.

Related

Error when reading inbox using O365 from python

I coded a simple python script to get the inbox of an user in my company's tenant. The licence in this specific user is an Office F3. Here is my code:
import O365
from O365 import Account, Connection, MSGraphProtocol, Message
scopes=['basic', 'message_all']
credentials=('user#domain', 'password')
account = Account(credentials = credentials)
if not account.is_authenticated: # will check if there is a token and has not expired
account.authenticate(scopes=scopes)
account.connection.refresh_token()
mailbox = account.mailbox()
inbox = mailbox.get_folder(folder_name='Inbox')
child_folders = inbox.get_folders(25)
for folder in child_folders:
print(folder.name, folder.parent_id)
for message in inbox.get_messages(5):
if message.subject == 'test':
print(message.body)
When I run it it tells me to copy and paste an url and when i click on it i get the following error:
CMD prompt when I run the code
AADSTS700016: Application with identifier 'x' was not found in the directory 'y'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.
Anyone knows how to fix it?
The answer comes a few months late, but if someone has the same problem, the person is happy to find the answer here.
Your error message is the default login link for o365 via the Graph API.
(The URL is wrong (%2F = /), probably due to an outdated version of the Jupyter Notebook?)
To stay logged in, I recommend specifying as scope: 'offline_access'. This will create a token that allows authentication without a login link.

Issue in getting authenticated on bitbucket, using python script

I'm trying to get all project list from bit bucket, using username and app password. But getting 401 error.
I'm using atlasian python library for client connection, and below is the code.
bitbucket = Bitbucket(url='https://api.bitbucket.org',username="",password="")
data = bitbucket.project_list()
for data in data:
print(data)
Even tried with bitbucket user name and password still same.
Is there any way to generate key or something which can be used all the time not like oauth as it has expiration time.
You need to use App passwords as mentioned here
Using an app password
An app password is a substitute password for your user account, when authenticating with Bitbucket:
your Bitbucket username (not email) which can be found in the settings
the app password

Flask-Mail on Google App Engine Flexible ENV

I'm trying to get Flask-Mail setup on in Flexible ENV on Google App Engine. Flask-Mail works on my localhost using the credentials for a domain I am trying to use to send the mail. However, when using it on GAE through my API it returns a 502 error, however it shows no error messages in the logs or console. Going through the documentation for GAE Flexible it doesn't mention anything about NOT being able to use it, however it doesn't show how one would setup Flask-Mail either.
I have this..
mail = Mail()
print('1') // We Get here
msg = Message("Hello",
sender="me#mydomain.com",
recipients=["me#mydomain.com"])
print('2') // We get here
msg.body = 'Testing'
print('3') // We get here
mail.send(msg)
print('4') // This never gets call because I timeout on a 502 before this
I can tell I am not getting any fatal errors because the app stays working. However this fails with the 502. I have tried adding my email to the list of authorized senders but it doesn't seem to have helped.
I would appreciate any feedback. If I forced to use a 3rd party service to send mail it may cause me to move the project off of GAE.
As Ivan posted on his comment, to send email from a GAE app you need to use a mail service. Right now there are 3 options for apps on a flexible environment: Mailgun, MailJet and SendGrid. Choose the one you see better for your app.
After setting up an account on the mail service you have chosen, you have to prepare your code by integrating the parts related to the mail service.
These tutorials should help you establish the mail service for your app:
Mailgun
MailJet
SendGrid
I've had the same error but on a virtual machine on the internet ( linode service ) and it turned out that it has some thing to do with rDNS and some domain name config that you have to set up for your Ip address to get things working correctly , check this
https://www.linode.com/community/questions/19082/i-just-created-my-first-linode-and-i-cant-send-emails-why

Missing redirect_uri error for Resource owner password credentials grant type

I am trying to write a script on Python that fetches my friend list from facebook. To fetch data, I need to get the access token. I am using requests_oauthlib package to achieve the same. Since I am not writing a web application, I have not used local webserver(no redirect url). I choose to use Resource owner password credentials grant type. I am getting error.
This is my code:
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import LegacyApplicationClient
FACEBOOK_APP_ID = '**********'
FACEBOOK_APP_SECRET = '*********'
username = 'Aman Mittal'
password = '****'
token_url = "https://graph.facebook.com/oauth/access_token"
oauth = OAuth2Session(client=LegacyApplicationClient(client_id=FACEBOOK_APP_ID))
oauth_access_token = oauth.fetch_token(token_url, client_secret=FACEBOOK_APP_SECRET,username=username, password=password, client_id=FACEBOOK_APP_ID)
When I run the script, it shows error - 'Missing access token parameter'
I went through traceback and realized that access token received is this:
{"error":{"message":"Missing redirect_uri parameter.","type":"OAuthException","code":191,"fbtrace_id":"CUSmQKT8YGb"}}
First of all, I don't understand while using Legacy Application client(Resource Owner password credentials grant type ), why do I need redirect uri?
If I do choose to start a webserver alongside using web.py or something else. How do I register it on Facebook? or Do I even need to?
PS. I am new to both Python and posting on Stack Overflow. Please try to explain with details and forgive me if I have committed any stupid mistake.
Facebook does not support the OAuth 2.0 Resource Owner Password Credentials grant type.

Basic authentication with jira-python

I'm new to Python, new to the jira-python library, and new to network programming, though I do have quite a bit of experience with application and integration programming and database queries (though it's been a while).
Using Python 2.7 and requests 1.0.3
I'm trying to use this library - http://jira-python.readthedocs.org/en/latest/ to query Jira 5.1 using Python. I successfully connected using an unauthenticated query, though I had to make a change to a line in client.py, changing
I changed
self._session = requests.session(verify=verify, hooks={'args': self._add_content_type})
to
self._session = requests.session()
I didn't know what I was doing exactly but before the change I got an error and after the change I got a successful list of project names returned.
Then I tried basic authentication so I can take advantage of my Jira permissions and do reporting. That failed initially too. And I made the same change to
def _create_http_basic_session
in client.py , but now I just get another error. So problem not solved. Now I get a different error:
HTTP Status 415 - Unsupported Media Type
type Status report
message Unsupported Media Type
description The server refused this request because the request entity is in
a format not` `supported by the requested resource for the requested method
(Unsupported Media Type).
So then I decided to do a super simple test just using the requests module, which I believe is being used by the jira-python module and this code seemed to log me in. I got a good response:
import requests
r = requests.get(the_url, auth=(my username , password))
print r.text
Any suggestions?
Here's how I use the jira module with authentication in a Python script:
from jira.client import JIRA
import logging
# Defines a function for connecting to Jira
def connect_jira(log, jira_server, jira_user, jira_password):
'''
Connect to JIRA. Return None on error
'''
try:
log.info("Connecting to JIRA: %s" % jira_server)
jira_options = {'server': jira_server}
jira = JIRA(options=jira_options, basic_auth=(jira_user, jira_password))
# ^--- Note the tuple
return jira
except Exception,e:
log.error("Failed to connect to JIRA: %s" % e)
return None
# create logger
log = logging.getLogger(__name__)
# NOTE: You put your login details in the function call connect_jira(..) below!
# create a connection object, jc
jc = connect_jira(log, "https://myjira.mydom.com", "myusername", "mypassword")
# print names of all projects
projects = jc.projects()
for v in projects:
print v
Below Python script connects to Jira and does basic authentication and lists all projects.
from jira.client import JIRA
options = {'server': 'Jira-URL'}
jira = JIRA(options, basic_auth=('username', 'password'))
projects = jira.projects()
for v in projects:
print v
It prints a list of all the project's available within your instance of Jira.
Problem:
As of June 2019, Atlassian Cloud users who are using a REST endpoint in Jira or Confluence Cloud with basic or cookie-based authentication will need to update their app or integration processes to use an API token, OAuth, or Atlassian Connect.
After June 5th, 2019 attempts to authenticate via basic auth with an Atlassian account password will return an invalid credentials error.
Reference: Deprecation of basic authentication with passwords for Jira and Confluence APIs
Solution to the Above-mentioned Problem:
You can use an API token to authenticate a script or other process with an Atlassian cloud product. You generate the token from your Atlassian account, then copy and paste it to the script.
If you use two-step verification to authenticate, your script will need to use a REST API token to authenticate.
Steps to Create an API Token from your Atlassian Account:
Log in to https://id.atlassian.com/manage/api-tokens
Click Create API token.
From the dialog that appears, enter a memorable and concise Label for your token and click Create.
Click Copy to clipboard, then paste the token to your script.
Reference: API tokens
Python 3.8 Code Reference
from jira.client import JIRA
jira_client = JIRA(options={'server': JIRA_URL}, basic_auth=(JIRA_USERNAME, JIRA_TOKEN))
issue = jira_client.issue('PLAT-8742')
print(issue.fields.summary)
Don't change the library, instead put your credentials inside the ~/.netrc file.
If you put them there you will also be able to test your calls using curl or wget.
I am not sure anymore about compatibility with Jira 5.x, only 7.x and 6.4 are currently tested. If you setup an instance for testing I could modify the integration tests to run against it, too.
My lucky guess is that you broke it with that change.
As of 2019 Atlassian has deprecated authorizing with passwords.
You can easily replace the password with an API Token created here.
Here's a minimalistic example:
pip install jira
from jira import JIRA
jira = JIRA("YOUR-JIRA-URL", basic_auth=("YOUR-EMAIL", "YOUR-API-TOKEN"))
issue = jira.issue("YOUR-ISSUE-KEY (e.g. ABC-13)")
print(issue.fields.summary)
I recommend storing your API Token as an environment variable and accessing it with os.environ[key].

Categories