I could get HTTP Basic Authentication to work using requests:
import requests
request = requests.post(url, auth=(user, pass), data={'a':'whatever'})
And also using urllib2 and urllib:
import urllib2, urllib
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, user, pass)
auth_handler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
content = urllib2.urlopen(url, urllib.urlencode({'a': 'whatever'}))
The problem is I get an unauthorized error when I try the same thing with mechanize:
import mechanize, urllib
from base64 import b64encode
browser = mechanize.Browser()
b64login = b64encode('%s:%s' % (user, pass))
browser.addheaders.append(('Authorization', 'Basic %s' % b64login ))
request = mechanize.Request(url)
response = mechanize.urlopen(request, data=urllib.urlencode({'a':'whatever}))
error:
HTTPError: HTTP Error 401: UNAUTHORIZED
The code I tried with mechanize could be trying to authenticate in a different way than the other two code snippets. So the question is how could the same authentication process be achieved in mechanize.
I am using python 2.7.12
The header should have been added to the request instead of the browser. In fact the browser variable isn't even needed.
import mechanize, urllib
from base64 import b64encode
b64login = b64encode('%s:%s' % (user, pass))
request = mechanize.Request(url)
request.add_header('Authorization', 'Basic %s' % b64login )
response = mechanize.urlopen(request, data=urllib.urlencode({'a':'whatever'}))
Related
I want to get response using Flask from OpenAI API. Whether I am getting Status 400 Bad Request from Browser through http://127.0.0.1:5000/chat
Bad Request
The browser (or proxy) sent a request that this server could not understand.
Also I am checking this from Postman
from flask import Flask, request, render_template
import requests
app = Flask(__name__)
#app.route('/')
def index():
return 'Welcome to ChatGPT app!'
#app.route('/chat', methods=['GET', 'POST'])
def chat():
user_input = request.form['text']
# Use OpenAI's API to generate a response from ChatGPT
response = generate_response_from_chatgpt(user_input)
return response
def generate_response_from_chatgpt(user_input):
api_key = "YOUR_API_KEY"
url = "https://api.openai.com/v1/engines/davinci/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"prompt": user_input,
"engine": "davinci"
}
response = requests.post(url, headers=headers, json=data)
return response.json()["choices"][0]["text"]
if __name__ == '__main__':
app.run()
It would be best if you check the openai documentation to make sure you are using the correct endpoint and data format in your request.
Also, you should check your API key, if it is correct and if you have reached the limit of requests.
Also, it's worth noting that the code you provided is missing the import statement for Flask. You will need to add the following line at the top of your file:
from flask import Flask, request
Also, I see that you're using request.form['text'] but you should check if the request is a GET or POST request.
if request.method == 'POST':
user_input = request.form['text']
else:
user_input = request.args.get('text')
This is to avoid a KeyError being raised when the request is a GET request.
I got this error in Flask Application:
curl http://0.0.0.0:8080/ -H "Authorization: Bearer TGazPL9rf3aIftplCYDTGDc8cbTd"
{
"msg": "Not enough segments"
}
Here a sample:
from flask import Flask
from flask_restful import Resource, Api
from flask_jwt_extended import JWTManager, jwt_required
app = Flask(__name__)
jwt = JWTManager(app)
api = Api(app)
class HelloWorld(Resource):
#jwt_required
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
Console:
* Serving Flask app "app.py" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 890-265-009
127.0.0.1 - - [26/Apr/2020 02:02:32] "GET / HTTP/1.1" 422 -
I can't understand: What's wrong?
The exception has been thrown in other lib (line 183 in site-packages/jwt/api_jws.py):
def _load(self, jwt):
if isinstance(jwt, text_type):
jwt = jwt.encode('utf-8')
if not issubclass(type(jwt), binary_type):
raise DecodeError("Invalid token type. Token must be a {0}".format(
binary_type))
try:
signing_input, crypto_segment = jwt.rsplit(b'.', 1)
header_segment, payload_segment = signing_input.split(b'.', 1)
except ValueError:
raise DecodeError('Not enough segments')
The token you are trying to pass in (TGazPL9rf3aIftplCYDTGDc8cbTd)is not a valid JWT. A valid JWT has three segments separated by dots: <base64_encoded_header>.<base64_encoded_payload>.<signature>. You can read more about it here: https://jwt.io/introduction/
I will post here an answer related to my initial problem above, the context is that I was trying to user flask_jwt_extend to use in firebase authentication, but I have this "Not enough segments" errors and I got blocked.
So after that, I change my code to:
from flask import Flask, request
from flask_restful import Resource, Api
from functools import wraps
import google.auth.transport.requests
import google.oauth2.id_token
app = Flask(__name__)
api = Api(app)
HTTP_REQUEST = google.auth.transport.requests.Request()
def jwt_required_gcp(fn):
#wraps(fn)
def wrapper(*args, **kwargs):
id_token = request.headers['Authorization'].split(' ').pop()
claims = google.oauth2.id_token.verify_firebase_token(
id_token, HTTP_REQUEST)
if not claims:
return 'Unauthorized', 401
return fn(*args, **kwargs)
return wrapper
class HelloWorld(Resource):
#jwt_required_gcp
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
Check your JWT Token. Is it valid?
#fresh_jwt_required - fresh_jwt_required() function to only allow fresh tokens to access the certain endpoint
#jwt_required - A decorator to protect a Flask endpoint with JSON Web Tokens. Any route decorated with this will require a valid JWT to be present in the request (unless optional=True, in which case no JWT is also valid) before the endpoint can be called.
For more detail review flask-jwt-extended
can anyone explain me to login to this link(ftpservice.acesphere.com) through python
The URL you are trying to access requires NTLM authentication. You can try python-ntlm package:
from ntlm import HTTPNtlmAuthHandler
import urllib2
url = "http://ftpservice.acesphere.com/stocks/indices/master/indicesmaster_new.ace"
user = r'domain\user'
password = "password"
pm = urllib2.HTTPPasswordMgrWithDefaultRealm()
pm.add_password(None, "http://ftpservice.acesphere.com/", user, password)
auth = HTTPNtlmAuthHandler.HTTPNtlmAuthHandler(pm)
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)
response = urllib2.urlopen(url)
print response.read()
You are getting this exception:
urllib2.HTTPError: HTTP Error 401: Unauthorized
This means that the website is returning an HTTP 401 Unauthorized status code. Either catch the exception or modify your request to not produce this error.
See also: urllib2 documentation
I am new to google python api client.I am learning from https://developers.google.com/api-client-library/python/start/get_started.I want to make an api which converts python object into JSON data and sends to a servlet.
The python code of file api.py:
import os
import urllib2
import httplib2
import json
import requests
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run_flow
from oauth2client.file import Storage
from oauth2client import tools
api_version='1'
_file_="D:\API"
CLIENT_SECRETS = os.path.join(os.path.dirname(_file_))
flow=flow_from_clientsecrets(CLIENT_SECRETS,
scope=[
'https://www.googleapis.com/auth/devstorage.full_control',
],
http = httplib2.Http()
auth_http = credentials.authorize(http)
service=build('SendNotif',api_version,http=http)
req = urllib2.Request('http://example/notify')
req.add_header('Content-Type', 'application/json')
data={"message":"Hello User you are notified"}
data_json = json.dumps(data)
response = urllib2.urlopen(req, json.dumps(data))
The error shown is:
D:\API>python api.py
File "api.py", line 25
auth_http = credentials.authorize(http)
^
SyntaxError: invalid syntax
please do help in correcting me..
thanks in advance....
You're missing a closing parenthesis for this line:
flow=flow_from_clientsecrets(CLIENT_SECRETS,
ok here is my code , what I am trying to do is post to a page that is password protected can you have a look at the code below at see where I am going wrong getting
!/usr/bin/python
import requests, sys, socket, json
from requests.auth import HTTPDigestAuth ,HTTPBasicAuth
172.168.101.214
params = {'#Generate': 'New'}
response = requests.post('https://TerraceQ.internal.ca/views/Debug_Dump/1', auth=HTTPDigestAuth('user', 'fakepassword'), data=params)
print response.status_code
there this worked
ip="172.168.99.99"
try:
response = requests.get('https://' + ip + '/views', auth=HTTPDigestAuth('username', 'password'), verify=False)
except urllib3.exceptions.SSLError as e:
sys.exit('test')