I have keycloak server running in docker (192.168.99.100:8080) and python flask-oidc flask application running locally ( localhost:5000) i am not able to access the protected Rest Api even after getting the access_token. has anyone tried this code. if so please help me regarding this. thank you
this is my keycloak client using docker jboss/keycloak image
this is my newuser under the new realm
below is my flask-application
app.py
from flask import Flask, g
from flask_oidc import OpenIDConnect
import requests
secret_key = os.urandom(24).hex()
print(secret_key)
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
app.config["OIDC_CLIENT_SECRETS"]="client_secrets.json"
app.config["OIDC_COOKIE_SECURE"]=False
app.config["OIDC_SCOPES"]=["openid","email","profile"]
app.config["SECRET_KEY"]=secret_key
app.config["TESTING"]=True
app.config["DEBUG"] = True
app.config["OIDC_ID_TOKEN_COOKIE_SECURE"]=False
app.config["OIDC_REQUIRED_VERIFIED_EMAIL"]=False
app.config["OIDC_INTROSPECTION_AUTH_METHOD"]='client_secret_post'
app.config["OIDC_USER_INFO_ENABLED"]=True
oidc = OpenIDConnect(app)
#app.route('/')
def hello_world():
if oidc.user_loggedin:
return ('Hello, %s, See private '
'Log out') % \
oidc.user_getfield('preferred_username')
else:
return 'Welcome anonymous, Log in'
client_secrets.json
{
"web": {
"issuer": "http://192.168.99.100:8080/auth/realms/kariga",
"auth_uri": "http://192.168.99.100:8080/auth/realms/kariga/protocol/openid-connect/auth",
"client_id": "flask-app",
"client_secret": "eb11741d-3cb5-4457-8ff5-0202c6d6b250",
"redirect_uris": [
"http://localhost:5000/"
],
"userinfo_uri": "http://192.168.99.100:8080/auth/realms/kariga/protocol/openid-connect/userinfo",
"token_uri": "http://192.168.99.100:8080/auth/realms/kariga/protocol/openid-connect/token",
"token_introspection_uri": "http://192.168.99.100:8080/auth/realms/kariga/protocol/openid-connect/token/introspect"
}
}
when i launch the flask-app in web browser
i click on the Log in link
next it prompts for the user details (user created under my new realm)
it takes a couple of seconds then it redirects me to an error page
http://localhost:5000/oidc_callback?state=eyJjc3JmX3Rva2VuIjogIkZZbEpqb3ZHblZoUkhEbmJsdXhEVW
that says
httplib2.socks.HTTPError
httplib2.socks.HTTPError: (504, b'Gateway Timeout')
and also it is redirecting to /oidc_callback which is not mentioned anywhere
any help would be appreciated
the problem is occuring because keycloak server which is running
in docker(192.168.99.100)
is not able to hit the flask application server which is running locally(localhost)
better to run both as services in docker by creating a docker-compose file
Related
I have my ionic app where I'd like to run my python code as a rest API, I used to do it with php but since python has many libraries available, it will be useful for many projects to exexute python code in server side instead of php.
I have manage my python code with flash with a simple Hello World code, and I can run it, so if I run python3 test.py (which is the name of my exemple code), inside my browser, if I go to http://localhost:5002 I have my result {"text": "Hello World!"}
from flask import Flask, request
from flask_cors import CORS, cross_origin
from flask_restful import Resource, Api
from json import dumps
from flask_jsonpify import jsonify
app = Flask(__name__)
api = Api(app)
CORS(app)
#app.route("/")
def hello():
return jsonify({'text':'Hello World!'})
if __name__ == '__main__':
app.run(port=5002)
Then, if I leave my console execute my python code and than in my ionic app I call my server :
export class Tab3Page implements OnInit {
constructor(private http: HttpClient) {
}
ngOnInit() {
var obj: JSON;
let headers = new HttpHeaders({'Content-Type': 'application/json; charset=UTF-8'});
let options = {headers:headers};
this.http.get('http://127.0.0.1:5002/').subscribe(data => {
console.log(data);
})
}
}
I am able to console log the same result, which is great.
What I'd like to do now, it to execute my python code from my ionic code without the python code running in the console.
This will be the need in the futur, since my code will be in server side, and then I need to open (call it) only when I need to execute something (like mysql request for example).
This is what i used to do it php :
this.http.get(this.server + `getUser.php?&id=${userId}`);
I'm trying to deploy example flask API app given in flask document in pythonanywhere.
from flask import Flask, request
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
todos = {}
class TodoSimple(Resource):
def get(self, todo_id):
return {todo_id: todos[todo_id]}
def put(self, todo_id):
todos[todo_id] = request.form['data']
return {todo_id: todos[todo_id]}
api.add_resource(TodoSimple, '/<string:todo_id>')
if __name__ == '__main__':
app.run()
When I was testing this app locally in pycharm, I executed app successfully by sending data using
curl http://localhost:5000/todo1 -d "data=Remember the milk" -X PUT
command in pycharm terminal.
The result I got is
{
"todo1": "Remember the milk"
}
But when I tested the deployment using Postman the result I got is
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again
Parameters used in Query params in Postman are:
key:data
value:"Remember the milk"
The result got when executed the app in locally is the correct result.
What am I doing wrong?
PS:
When using the pythonanywhere I used
http://www.mydomain.pythonanywhere.com
You need to replace http://localhost:5000/ with the url from pythonanywhere, e.g.
http://yourusername.pythonanywhere.com
That is assuming you didn't pay and configure your own domain
Data has to be send in 'Body' tab, not in 'Param' tab.
I am an absolute beginner in chat bot. I am learning on my own and went on developing a very simple chat bot using Dialog flow. I have a python code for responding the request to my Dialog flow bot. I have enabled "webhook" in fulfillment and also enabled in "Intent".My ngrok url is http://ae3df23b.ngrok.io/. I have written a function in my python code which respond to ngrok which connects Dialog flow. Now problem is that It is showing error "404 not found" and The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. Please help me guys. Thanks in advance.
My code is
#import necessary packages and libraries
import urllib
import os
import json
from flask import Flask
from flask import request
from flask import make_response
app=Flask(__name__)
#app.route('/webhook', methods=['POST'])
def webhook():
req=request.get_json(silent=True, force=True)
print("Request:")
print(json.dumps(req, indent=4))
res=makeWebhookResult(req)
res=json.dumps(res, indent=4)
print(res)
r=make_response(res)
r.headers['Content-Type']='application/json'
return r
def makeWebhookResult(req):
if req.get("result").get("action")!="interest":
return {}
result=req.get("result")
parameters=result.get("parameters")
name=parameters.get("Banknames")
bank={'SBI':'10%', 'HDFC Bank':'9%', 'Bank of Baroda':'11', 'Federal Bank':'8.9%', 'ICICI Bank': '11.5%'}
speech='The interest rate of '+ name + "is" + str(bank[name])
print("Response:")
print(speech)
return {
"speech":speech,
"displayText":speech,
"source":"BankInterestRates"
}
if __name__ == "__main__":
port=int(os.getenv('PORT', 80))
print("Starting app on port %d", (port))
app.run(debug=True, port=port, host='0.0.0.0')
I think you should use https://ae3df23b.ngrok.io/webhook. You are missing the path. Also, use https and generate a new ngrok URL and update the fulfilment.
Try using this format instead https://ae3df23b.ngrok.io/[replace-with-your-project-id]/us-central1/dialogflowFirebaseFulfillment
and make sure u start ngrok with port 5000 and host your functions with "firebase serve" command
My backend is an AWS EC2 server that runs on flask, I'm trying to port over my code from http to https. I've used letsencrypt and certbot to create valid certificates. My flask backend accesses the certs and then calls the host. I tried adding SSLify after looking through other posts ( and seeing that it can be used with Flask, but it didn't change anything.
from flask_cors import CORS
from flask_sslify import SSLify
from OpenSSL import SSL
app = Flask(__name__)
CORS(app)
sslify = SSLify(app)
sslify
if __name__ == "__main__":
context = ("../../../../etc/letsencrypt/live/app.mydomain.name/fullchain.pem","../../../../etc/letsencrypt/live/app.mydomain.name/p$
app.run(host='127.0.0.1', port=5000, debug=True, ssl_context=context)
On the React frontend side, I'm using axios
axios.post('https://127.0.0.1:5000/run_query', postData, axiosConfig)
.then(function (response) {
console.log("Successful connection");
console.log(response.data);
influencerList = response.data.query_results;
console.log(influencerList);
currentComponent.setState({IL: influencerList});
})
.catch(function (error) {
console.log(error);
});
using app.run options I listed above on the backend returns
xhr.js:178 OPTIONS https://127.0.0.1:5000/run_query net::ERR_CONNECTION_REFUSED in the Google Chrome Browser Console.
I'm runnning nginx on Linux AMI. The certificates are for RehlOS/CentOS generated through letsencrypt and certbot. My Nginx error.log doesn't return anything, running the backend python file doesn't log anything anymore, like it did before going from HTTP. It just displays this:
* Running on https://ec2-34-209-86-220.us-west-2.compute.amazonaws.com:5000/ (Press CTRL+C to quit)
* Restarting with stat
I also tried changing the post URL to https://ec2-34-209-86-220.us-west-2.compute.amazonaws.com:5000/run-query instead of https://127.0.0.1:5000/run_query but got the exact same error.
I hope it's something simple, any help would be great. Thanks!
I'm having a hard time integrating create-react-app single page application to my flask backend. I want to be able to make a fetch/axios call from my front end like so: axios.get('/getResults') and fetch('/getResults'). Some things I have tried but not limited to is specifying the Flask port as 3000 which is the same used by create-react-app. Also, used the proxy configuration feature on the "package.json" file of create-react-app but to no avail. I suspect my folder structure and Flask code implementation may likely be causing this. Below is my folder structure and "app.py" code. Any help I could get will be appreciated. I can provide additional information if necessary. Thanks
Project -build(contains static folder, index.html...Other meta files)-node_modules-public-srcapp.pypackage.jsonrequirements.txt
app.py:
from flask import Flask, Response, request, jsonify, make_response, send_from_directory,render_template
app = Flask(__name__, static_path='/build/static/')
app.debug=True
#app.route('/')
def root():
print('Inside root function')
return app.send_static_file('index.html')
#app.route('/getResults', methods=["GET"])
def results():
print('Inside getResults path')
return app.send_static_file('index.html')
#app.route('/postData', methods=["POST"])
def data_results():
print('Inside postData path')
data = request.get_json
return jsonify(data)
#app.route('/<path:path>')
def send_js(path):
print("inside send_js fxn")
return send_from_directory('./build/static',path)
if __name__ == "__main__":
print("inside main host call")
app.run(host='0.0.0.0', port=3000)
Errors I get when I run "python app.py" are:
On the terminal: Inside root function
127.0.0.1 - - [12/Jun/2017 09:42:24] "GET / HTTP/1.1" 404 -
On the browser:Not Found - The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I was having the exact same issue and I was able to solve it by appeasing Flask with symlinks.
Keep the templates and static directory paths at their defaults and in the directory with your Flask main file, add these symlinks
ln -s build/ templates
ln -s build/static static
In case you were curious, this was my specific problem, which just involved a few more nested directories but was in essence the same:
Running NPM Build from Flask
You can then use Nurzhan's root configuration:
#app.route('/')
def root():
print('Inside root function')
return render_template('index.html')
But you only require your app declaration to be: app = Flask(__name__)
The only thing that doesn't work for me is the favicon, and I will update this answer once I figure that out.
In development mode, you need to configure your create-react-app package.json to forward "ajax" request to the flask server.
Here is what my package.json looks like:
{
"name": "socialite",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:8080",
"devDependencies": {
"react-scripts": "1.0.10"
},
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
See the proxy field? That's where the magic happens, replace its value with the flask server address. That way, you can take advantage of CRA hot reloading feature. This is documented at in create-react-app as "Proxying API Requests in Development"
Then do run your application, you go at localhost:3000 or whatever port yarn opens for you. And when you do an API call in javascript over the rainbow to the server for instance: fetch('/api/model/') or something nodejs' server will forward to the flask app. I think the nodejs server does look at the content-type field of the ajax request to know whether it should forward the request to the backend server or not.
I recommend you prefix all your backend routes with something like /api/v1/ or something so the nginx configuration is neat and easy to write.
I think you have a number of misunderstandings.
The create-react-app runs on its own server on port 3000 and if you try to run your flask app on the same port on the same machine it will complain that port 3000 is already in use. So from this we move to another question - the structure of your application.
Will it be a separate reactjs based client on the frontend and api based on flask in the backend which will be 2 separate applications communicating with each other over HTTP? In this case the frontend and backend will usually run on separate servers.
Or it will one flask application which will use reactjs in its template pages?
You can fix your current problem with not finding URL by changing to this in your code:
#app.route('/')
def root():
print('Inside root function')
return render_template('index.html')
And this:
template_dir = os.path.abspath('build/templates')
app = Flask(__name__, static_path='/build/static/',
template_folder=template_dir)
Since your templates folder is in the build directory.