trying to forward request with chalice - python

im trying to build a simple api+lambda with chalice which can receive a POST request and then forward it to another API while adding some authentication. when i run my chalice code locally i can send a request and print the payload which i sent inside chalice console yet i cannot forward my request. i don't get back any errors or other print statements which i have in my code. i don't know where else to look for more answers so im asking here.
from chalice import Chalice
import requests
app = Chalice(app_name='redirect_url')
app.debug = True
TOKEN_URL = "https://redirect.com/v0/token"
USERNAME = 'email#email.com'
PASSWORD = 'Password01021'
#app.route('/redirect_url', methods=['POST'])
def get_payload():
update_payload = app.current_request.json_body
print(update_payload)
def fetch_auth_token():
username = USERNAME
password = PASSWORD
data = {
"grant_type": "password",
"username": username,
"password": password
}
response = requests.post(TOKEN_URL, data=data)
token = response.json()
print(token)
IF I send a request to the endpoint (http://127.0.0.1:8000/redirect_url) I see my request printed inside chalice logs, but i don't see the token request.
I would appreciate any help

This is a bit old, but I thought I would answer it for the community for those new to Chalice.
You are expecting to fire the function without calling it. It should be:
from chalice import Chalice
import requests
app = Chalice(app_name='redirect_url')
app.debug = True
TOKEN_URL = "https://redirect.com/v0/token"
USERNAME = 'email#email.com'
PASSWORD = 'Password01021'
#app.route('/redirect_url', methods=['POST'])
def get_payload():
update_payload = app.current_request.json_body
APIresponse = fetch_auth_token()
print(APIresponse) ## If you want to show it right before the update_payload
print(update_payload)
def fetch_auth_token():
username = USERNAME
password = PASSWORD
data = {
"grant_type": "password",
"username": username,
"password": password
}
response = requests.post(TOKEN_URL, data=data)
return response.json()

Related

Python - OAUTH2 How to get access token using PCKE?

I am trying to get this access token with Python. With Postman I can get an access token. After configurations in the screenshots, I click the Get Access Token button, and A pop-up throws for username and password. Then I fill them. After that, I can get an access token from Postman.
To get an access token with Python, I wrote the code below. In the first get request, I get the cookies and Redirect URL(to post user credentials). Then, I post user credentials and cookies to Redirected URL. After that, the response header["location"] must include a code parameter to get the token. But, the header parameter does not have a code parameter. It has an Authorization URL with query parameters. How can get this code parameter? Finally, I will post a request(to token URL) with this code to get an access token on the response body.
import base64
import hashlib
import json
import os
import re
import urllib.parse
import requests
from bs4 import BeautifulSoup
from rich import print
username = 'username '
password = 'password '
client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
client_secret = 'yyyyyyyyyyyyyyyyyyyyyyyyyy'
prod_url = 'https://url:port'
callback_url = prod_url + '/main/ifsapplications/projection/oauth2/callback'
authorization_url = prod_url + '/openid-connect-provider/idp/authorization'
token_url = prod_url + '/openid-connect-provider/idp/token'
code_challenge_method = "S256" #SHA-256
scope = 'openid'
response_type ='code'
#Add auth data to request headers
#Grant type = authorization code with pkce
#send client credentials in body
code_verifier = base64.urlsafe_b64encode(os.urandom(40)).decode('utf-8')
code_verifier = re.sub('[^a-zA-Z0-9]+', '', code_verifier)
code_challenge = hashlib.sha256(code_verifier.encode('utf-8')).digest()
code_challenge = base64.urlsafe_b64encode(code_challenge).decode('utf-8')
code_challenge = code_challenge.replace('=', '')
resp = requests. Get(
url=authorization_url,
params={
"response_type": response_type,
"client_id": client_id,
"scope": scope,
"redirect_uri": callback_url,
"code_challenge": code_challenge,
"code_challenge_method": code_challenge_method,
},
allow_redirects=False
)
cookie = resp.headers['Set-Cookie']
cookie = '; '.join(c.split(';')[0] for c in cookie. Split(', '))
soup = BeautifulSoup(resp.text, 'html.parser')
form_action = soup. Find('a').text
resp = requests. Post(
url=form_action,
data={
"username": username,
"password": password
},
headers={"Cookie": cookie,
"Referer": form_action},
allow_redirects=False
)
redirect = resp.headers['Location']
print(resp.text)
print(resp.headers)
OUTPUT:

Firebase & Pyrebase can't write to database with Authentication

I am farely new to Pyrebase and Firebase and I was wondering why this code isn't working.
I want to write to the realtime database, for that the rules are
{
"rules": {
"userdata": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
And the python code is:
def login():
email = input("Enter email: ")
password = input("Enter password: ")
user = auth.sign_in_with_email_and_password(email, password)
user = auth.refresh(user['refreshToken'])
uid_variable = user['userId']
print(uid_variable)
print("Successfully logged in!")
data = {"test": "test"}
db.child("userdata").child(uid_variable).set(data)
But when it tries to write to the database it shows:
[Errno 401 Client Error: Unauthorized for url: https://xxxxxxxxxx-default-rtdb.europe-west1.firebasedatabase.app/userdata/xxxxxxxxxxxxxxxxxxxxxxxx.json] {
"error" : "Permission denied"
}
I don't seem to find any help anywhere so anything would be appreciated!
Depending on what you're using with your backend, this post on how to integrate Firebase Auth with a FastAPI backend using Pyrebase and Firebase Admin shows how you can create a login with Pyrebase using username and password
Based on the code here:
#app.post("/login", include_in_schema=False)
async def login(request: Request):
req_json = await request.json()
email = req_json['email']
password = req_json['password']
try:
user = pb.auth().sign_in_with_email_and_password(email, password)
jwt = user['idToken']
return JSONResponse(content={'token': jwt}, status_code=200)
except:
return HTTPException(detail={'message': 'There was an error logging in'}, status_code=400)
I believe you need to call the auth() function with the pyrebase object you created.

How to authenticate user in socket io Python using JWT,

working on a project in socket io python and JWT for tokens. Can enyone please help on how to authenticate user using JWT in socketio python. And I am also getting error while generating JWT token. The error is on line
response_data['data']['token'] = token //response data is refered before assignment
How to solve this error and below is my code:
encrypted_password, col_name = DBHandler.SignIn(email)
if encrypted_password:
encrypted_password = encrypted_password[0][0].encode()
f = Fernet(key)
encrypted_password = f.decrypt(encrypted_password).decode()
if password == encrypted_password:
token = jwt.encode({'user': email, 'exp': datetime.utcnow() + timedelta(minutes=600)}, private_key,
algorithm='HS256')
print(token)
response_data['data']['token'] = token
return jsonify(response_data)
else:
print('Incorrect Password')
response_data = {
"status": "Error",
"message": "Error in Getting User from DB",
"data": {}
}
return make_response(jsonify(response_data), 400)

Authenticating FastAPI session via requests

I am following the fastapi docs to implement an user authentication system. Here is a minimal example of app.py:
# import lines and utilities omitted
#app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
#app.get("/user/me", response_model=UserRead)
def read_user(*, session=Depends(get_session), current_user=Depends(get_current_user)):
user = session.get(User, current_user.username)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
When the user calls /users/me, it returns the current user. This works completely well as described in the tutorial in the SwaggerUI. But, I am not able to perform the same authorization and operation via python requests. Here is a following python code which I used:
import requests
backend_url = "http://localhost:8000/"
login_data = {'username':'user1', 'password':'secret1'}
s = requests.Session()
s.post(backend_url + "token", login_data) # response 200
s.get(backend_url + "user/me") # response 401
I am looking for some ways by which I can reuse the access_token returned by fastapi.
I found the answer in docs of fastapi itself:
import requests
backend_url = "http://localhost:8000/"
login_data = {'username':'user1', 'password':'secret1'}
session = requests.Session()
response = session.post(backend_url + "token", login_data)
response = json.loads(response.content.decode('utf-8'))
session.headers.update({"Authorization": 'Bearer ' + response['access_token']})
session.get(backend_url + "user/me")
You are not using the session variable s = requests.Session() to send HTTP requests.
So the post and get methods are getting sent independently from each other.
Try using
s = requests.Session()
s.post(backend_url + "token", login_data) # use the session post method
s.get(backend_url + "user/me") # use the session get method

Flask session does't work - react & flask app

I'm working on an app with flask backend and react front,
I want to save the username in a session and display it in the front post-login.
here is the current process:
configurations at the head of app.py (flask-server main file)
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "key"
app.config["SECRET_KEY"] = "pass"
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=1)
app.config["SESSION_TYPE"] = 'filesystem'
app.config["SESSION_PERMANENT"] = False
# app.config.from_object(__name__)
CORS(app)
Session(app)
jwt = JWTManager(app)
Login button with handler:
const data = {
username: loginForm.username,
password: loginForm.password
}
fetch("http://localhost:5000/token", {
method: "POST",
body: JSON.stringify(data)
})
.then((response) => {...
the route for "/token" - if the credentials are ok it renders my user homepage, and it works fine.
#app.route('/token', methods=["POST"])
def create_token():
username = json.loads(request.data)["username"]
password = json.loads(request.data)["password"]
sql_string = f"""select username, password from admins where username='{username}'"""
result = sql_call(sql_string) //this is a helper functino in db_connector file
if(result):
session["username"] = username
access_token = create_access_token(identity=username) //another helper function
response = app.response_class(response=json.dumps({"access_token": access_token}),
status=200,
mimetype='application/json')
response.headers.add('Access-Control-Allow-Origin', '*')
return response
on the app main page i have a span of "Hello " that tries to fetch the username from the session, sending request to route "/username":
#app.route("/username")
def getUsername():
username = session["username"]
response = jsonify({"username": "admin"})
return response
But it finds no key "username" in the session, and also the SID in 4 and SID in 3 are different.
how can I retrieve this data back?
my flask runs on port 5000 and react on port 3000,
thanks
In step 4 use this to get username
session.get("username")
Ok, I didn't manage to fix it,
session.get("username" also didn't work)
I noticed that the server is working fine when sending requests from postman, so the problem might be in React.
I used the get_jtw()
over the session and it works well :)

Categories

Resources