Amazon Lightsail Oauth2 Google signup generates Error: invalid_request Permission denied - amazon-web-services

#app.route('/login')
def showLogin():
state = ''.join(random.choice(string.ascii_uppercase + string.digits)
for x in xrange(32))
login_session['state'] = state
# return "The current session state is %s" % login_session['state']
return render_template('login.html', STATE=state)
#app.route('/gconnect', methods=['POST'])
def gconnect():
# Validate state token
if request.args.get('state') != login_session['state']:
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Obtain authorization code
code = request.data
try:
# Upgrade the authorization code into a credentials object
oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
oauth_flow.redirect_uri = 'postmessage'
credentials = oauth_flow.step2_exchange(code)
except FlowExchangeError:
response = make_response(
json.dumps('Failed to upgrade the authorization code.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Check that the access token is valid.
access_token = credentials.access_token
url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
% access_token)
h = httplib2.Http()
result = json.loads(h.request(url, 'GET')[1])
# If there was an error in the access token info, abort.
if result.get('error') is not None:
response = make_response(json.dumps(result.get('error')), 500)
response.headers['Content-Type'] = 'application/json'
return response
# Verify that the access token is used for the intended user.
gplus_id = credentials.id_token['sub']
if result['user_id'] != gplus_id:
response = make_response(
json.dumps("Token's user ID doesn't match given user ID."), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Verify that the access token is valid for this app.
if result['issued_to'] != CLIENT_ID:
response = make_response(
json.dumps("Token's client ID does not match app's."), 401)
print "Token's client ID does not match app's."
response.headers['Content-Type'] = 'application/json'
return response
stored_access_token = login_session.get('access_token')
stored_gplus_id = login_session.get('gplus_id')
if stored_access_token is not None and gplus_id == stored_gplus_id:
response = make_response(json.dumps('Current user is connected'), 200)
response.headers['Content-Type'] = 'application/json'
return response
# Store the access token in the session for later use.
login_session['access_token'] = credentials.access_token
login_session['gplus_id'] = gplus_id
# Get user info
userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
params = {'access_token': credentials.access_token, 'alt': 'json'}
answer = requests.get(userinfo_url, params=params)
data = answer.json()
login_session['username'] = data['name']
login_session['picture'] = data['picture']
login_session['email'] = data['email']
# See if a user exists, if it doesn't make a new one
user_id = getUserID(login_session['email'])
if not user_id:
user_id = createUser(login_session)
login_session['user_id'] = user_id
output = ''
output += '<h1>Welcome, '
output += login_session['username']
output += '!</h1>'
output += '<img src="'
output += login_session['picture']
output += ' " style = "width: 300px; height: 300px;border-radius: 150px;'
output += '-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
print "done!"
return output
I ran this OAuth code on my local machine. It worked but on Amazon Lightsail instance it gave the following error:
*Error: invalid_request Permission denied to generate login hint for target domain.
I even corrected my Redirect Uris and JAVA Script Origins to .com but it still gives the same error even on erasing the cookies.

Related

I am trying to make an api request to another app in django but in the same project, how do i pass the url to my api view, local deployment is working

```
def getpk(request, pk):
current_user = request.user
obj = LetterBody.objects.get(id=pk)
company = obj.company_details.short_code
location = obj.company_details.location.short_code
datetime = str(date.today())
token = Token.objects.get(user=current_user.id)
url = request.build_absolute_uri(reverse('create'))
payload={
'company':company,
'location':location,
'date':datetime
}
headers = {
'Authorization': f'token {token}',
'Content-Type': 'application/json'
}
if obj.reference_code:
return redirect('letters')
else:
response =requests.request( 'POST',url, headers=headers,
data=json.dumps(payload))
data = json.loads(response.text)
objid =data.get('id')
obj.reference_code = str(location) + "/" + company + "/" + str(datetime) + "/" +
str(objid)
obj.save()
return redirect('letter_detail', obj.id)
local production is working just fine but once i deploy the api is not working.create is the name to my create url in the api aplication

unset_jwt_cookies not deleting cookies

Config
app.config['JWT_COOKIE_CSRF_PROTECT'] = True
app.config["JWT_TOKEN_LOCATION"] = ['cookies']
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=0.005)
class LogOut(Resource):
#jwt_required()
def get(self):
response = make_response(render_template('home.html', is_login=False))
unset_jwt_cookies(response)
return response
#app.after_request
def refresh_expiring_jwts(response):
try:
exp_timestamp = get_jwt()["exp"]
now = datetime.now(timezone.utc)
target_timestamp = datetime.timestamp(now + timedelta(minutes=30))
if target_timestamp > exp_timestamp:
access_token = create_access_token(identity=get_jwt_identity())
set_access_cookies(response, access_token)
return response
except (RuntimeError, KeyError):
# Case where there is not a valid JWT. Just return the original respone
return response
I am trying to write code for implict refresh of access tokens using Flask-JWT-Extended library and having the below error.
In the above code login is working properly but if we access the logout the access token cookies are not being deleted.
Can anyone explain why it is not working?

How to fetch data from OMS workspace

I read the documentation yesterday and done some coding with python to fetch data in the following way. It's working fine.
import logging as log
import adal
import requests
import json
import datetime
from pprint import pprint
# Details of workspace. Fill in details for your workspace.
resource_group = 'Test'
workspace = 'FirstMyWorkspace'
# Details of query. Modify these to your requirements.
query = "Type=*"
end_time = datetime.datetime.utcnow()
start_time = end_time - datetime.timedelta(hours=24)
num_results = 2 # If not provided, a default of 10 results will be used.
# IDs for authentication. Fill in values for your service principal.
subscription_id = '{subscription_id}'
tenant_id = '{tenant_id}'
application_id = '{application_id}'
application_key = '{application_key}'
# URLs for authentication
authentication_endpoint = 'https://login.microsoftonline.com/'
resource = 'https://management.core.windows.net/'
# Get access token
context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id)
token_response = context.acquire_token_with_client_credentials('https://management.core.windows.net/', application_id, application_key)
access_token = token_response.get('accessToken')
# Add token to header
headers = {
"Authorization": 'Bearer ' + access_token,
"Content-Type": 'application/json'
}
# URLs for retrieving data
uri_base = 'https://management.azure.com'
uri_api = 'api-version=2015-11-01-preview'
uri_subscription = 'https://management.azure.com/subscriptions/' + subscription_id
uri_resourcegroup = uri_subscription + '/resourcegroups/'+ resource_group
uri_workspace = uri_resourcegroup + '/providers/Microsoft.OperationalInsights/workspaces/' + workspace
uri_search = uri_workspace + '/search'
# Build search parameters from query details
search_params = {
"query": query,
"top": num_results
}
# Build URL and send post request
uri = uri_search + '?' + uri_api
response = requests.post(uri, json=search_params,headers=headers)
# Response of 200 if successful
if response.status_code == 200:
# Parse the response to get the ID and status
data = response.json()
if data.get("__metadata", {}).get("resultType", "") == "error":
log.warn("oms_fetcher;fetch_job;error: " + ''.join('{}={}, '.format(key, val) for key, val in
data.get("error", {}).items()))
else:
print data["value"]
search_id = data["id"].split("/")
id = search_id[len(search_id)-1]
status = data["__metadata"]["Status"]
print status
# If status is pending, then keep checking until complete
while status == "Pending":
# Build URL to get search from ID and send request
uri_search = uri_search + '/' + id
uri = uri_search + '?' + uri_api
response = requests.get(uri, headers=headers)
# Parse the response to get the status
data = response.json()
status = data["__metadata"]["Status"]
print id
else:
# Request failed
print (response.status_code)
response.raise_for_status()
Today I went to the same webpage that I have followed yesterday but there is a different documentation today. So do I need to follow the new documentation? I tried new documentation too but got into an issue
url = "https://api.loganalytics.io/v1/workspaces/{workspace_id}/query"
headers = {
"X-Api-Key": "{api_key}",
"Content-Type": 'application/json'
}
search_param = {
}
res = requests.post(url=url, json=search_param, headers=headers)
print res.status_code
print res.json()
{u'error': {u'innererror': {u'message': u'The given API Key is not
valid for the request', u'code': u'UnsupportedKeyError'}, u'message':
u'Valid authentication was not provided', u'code':
u'AuthorizationRequiredError'}}
Here is the link to documentation
The api_key is not oms primary key on Portal. You could check example in this link. The token should like below:
Authorization: Bearer <access token>
So, you need modify X-Api-Key": "{api_key} to Authorization: Bearer <access token>.
You need create a service principal firstly, please check this link.
Then, you could use the sp to get token, please check this link.
Note: You could your code to get token, but you need modify the resource to https://api.loganalytics.io. Like below:
# Get access token
context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id)
token_response = context.acquire_token_with_client_credentials('https://api.loganalytics.io', application_id, application_key)
access_token = token_response.get('accessToken')
# Add token to header
headers = {
"Authorization": 'Bearer ' + access_token,
"Content-Type": 'application/json'
}
Working Prototype to Query OMS or Log Analytic workspace.
import adal
import requests
import json
import datetime
from pprint import pprint
# Details of workspace. Fill in details for your workspace.
resource_group = 'xxx'
workspace = 'xxx'
workspaceid = 'xxxx'
# Details of query. Modify these to your requirements.
query = "AzureActivity | limit 10"
# IDs for authentication. Fill in values for your service principal.
subscription_id = 'xxxx'
# subscription_id = 'xxxx'
tenant_id = 'xxxx'
application_id = 'xxxx'
application_key = 'xxxxx'
# Get access token
context = adal.AuthenticationContext('https://login.microsoftonline.com/' + tenant_id)
token_response = context.acquire_token_with_client_credentials('https://api.loganalytics.io', application_id, application_key)
access_token = token_response.get('accessToken')
# Add token to header
headers = {
"Authorization": 'Bearer ' + access_token,
"Content-Type": 'application/json'
}
search_params = {
"query": query
}
url = "https://api.loganalytics.io/v1/workspaces/{workspaceID}/query"
res = requests.post(url=url, json=search_params, headers=headers)
print (res.status_code)
print (res.json())

Why HttpResponseRedirect.set_cookie is not working when i use in django project?

When I use Google OAuth to verify my user, After verify is passed, I want to redirect to the page which user visit before authority, So I want to save the page path to user's cookie, so I implementation like this:
def get_login_resp(request, redirect):
print(redirect)
auth_url = "https://accounts.google.com/o/oauth2/auth?" + urlencode({
"client_id": GOOGLE_CLIENT_ID,
"response_type": "code",
"redirect_uri": make_redirect_url(request, redirect),
"scope": "profile email",
"max_auth_age": 0
})
resp = HttpResponseRedirect(auth_url)
max_age = 3600 * 24
expires = datetime.strftime(datetime.utcnow() + timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
print(expires)
resp.set_cookie('google_auth_redirect', redirect, max_age=max_age, expires=expires,
domain=LOGIN_COOKIE_DOMAIN, secure=True, httponly=True)
print(resp._headers)
print(resp.cookies)
return resp
ps: redirect is the page path which I want to save
But when request the login url with Postman, I can only see this headers:
response headers
And these cookies:
Cookies
So how can i do with this problem? There is not any error info for me.
Try every methods to find out what's wrong, But still failed.
So I try to run server on an other machine(a Linux server), it works!!!
BTW: My develop PC is Macbook Pro 15-inch, 2017 with macOS High Sierra 10.13.1
Update at 14/Jan/2020:
Didn't find the root cause, but I solved this issue by saving redirect_url to session data, in this solution you should check auth valid by using another request, then call google auth to reauth again, code like below:
class GoogleAuthView(RedirectView):
# google auth view
def get(self, request, *args, **kwargs):
# get redirect url from url params, frontend code should pass the param in request url
redirect_url = request.GET.get('redirect_url', None)
if redirect_url:
redirect_url = parse.unquote(redirect_url)
credentials = request.session.get("credentials", None)
if (not credentials) or ('expire_time' not in credentials) or (credentials['expire_time'] < time.time()):
request.session['redirect_url'] = redirect_url # if need google auth, save redirect url to session first
else:
if redirect_url:
return HttpResponseRedirect(redirect_url)
flow = google_auth_oauthlib.flow.Flow.from_client_config(
client_config=settings.GOOGLE_AUTH_CONFIG,
scopes=settings.GOOGLE_AUTH_SCOPES
)
flow.redirect_uri = settings.GOOGLE_AUTH_CONFIG['web']['redirect_uris'][0]
authorization_url, state = flow.authorization_url(
access_type='offline',
include_granted_scopes='true'
)
request.session['state'] = state
return HttpResponseRedirect(authorization_url)
class GoogleAuthCallBackView(BasicView):
# google callback view
def get(self, request, *args, **kwargs):
state = request.session.get('state')
flow = google_auth_oauthlib.flow.Flow.from_client_config(
client_config=settings.GOOGLE_AUTH_CONFIG,
scopes=settings.GOOGLE_AUTH_SCOPES,
state=state
)
flow.redirect_uri = settings.GOOGLE_AUTH_CONFIG['web']['redirect_uris'][0]
# get redirect url from session data if exists
redirect_url = request.session.get('redirect_url') or settings.ADMIN_LOGIN_REDIRECT_URL
response = HttpResponseRedirect(redirect_url)
try:
del request.session['redirect_url']
except KeyError:
logger.info('Delete `redirect_url` in session get KeyError.')
pass
try:
flow.fetch_token(authorization_response=request.build_absolute_uri())
except Exception as e:
logger.error(e.message)
return response
# save credentials to session
credentials = flow.credentials
request.session["credentials"] = {
'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes,
'expire_time': time.time() + TOKEN_EXPIRE_TIME,
}
profile_client = googleapiclient.discovery.build(
serviceName='oauth2',
version='v2',
credentials=credentials
)
profile = profile_client.userinfo().v2().me().get().execute()
email = profile['email']
user = user_manager.get_user_by_email(email)
if user:
user.username = profile['name'] # sync username from google
user.picture = profile['picture'] # sync avatar from google
user.save()
request.session["user"] = user.to_dict()
else:
return HttpResponseRedirect("/api/non_existent_user/") # show non-existent user
return response

Logging in using Python 3

How to login to a site say http://www.example.com/ given I have a username and a password and retreive Cookies for further usage in Python 3?
Here is a code snippet I used in python to log into a web page:
base_url = "http://www.example.com"
store = 01234
username = 'myusername'
password = 'mypassword'
post_data = {
'hdnAction': 'LOGIN',
'txtStoreID': '%s' % store,
'txtLogin': '%s' % username,
'txtpassword': '%s' % password,
'txtNumLines':'10',
'btnLogin':'Login',
'hdnCount':'0'
}
params = urllib.urlencode(post_data)
request = urllib2.Request(base_url + "/", params)
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
#print "getting url: %s" % request.get_full_url()
response = urllib2.urlopen(request, params, 300)
xmldata = response.read()
redirects = re.compile('''window\.location\.href="(.*?)"''', re.DOTALL).findall(xmldata)
cookie = response.headers.get('Set-Cookie').split(';')[0].strip() + ";"
if len(redirects) > 0 :
request = urllib2.Request(base_url + "%s" % redirects[0])
print "getting url: %s" % request.get_full_url()
request.add_header('cookie', cookie)
response = urllib2.urlopen(request, None, 300)
xmldata = response.read()
Those things in post data are elements on the HTML FORM tag. Look at thier "name" attributes.