How to check for an HTTP status code of 401? - google-app-engine

In one of the answers that I have received here, I encountered a problem of not knowing how to pass automatically through "Google App Engines" my ID and a password to a website, on which I am a registered user and have an account. A suggestion was given to me to "check for an HTTP status code of 401, "authorization required", and provide the kind of HTTP authorization (basic, digest, whatever) that the site is asking for". I don't know how to check for status code. Can anyone, please, tell me how to do it?
+++++++++++++++++++++++++++++++++
Additional Information:
If I use this way in Google App Engine (fetching the url of my eBay summary page):
from google.appengine.api import urlfetch
url = "http://my.ebay.com/ws/eBayISAPI.dll?MyEbay&gbh=1&CurrentPage=MyeBaySummary&ssPageName=STRK:ME:LNLK"
result = urlfetch.fetch(url)
if result.status_code == 200:
print "content-type: text/plain"
print
print result.status_code
I always get "200" instead of "401"

In ordinary Python code, I'd probably use the lower-level httplib, e.g.:
import httplib
domains = 'google.com gmail.com appspot.com'.split()
for domain in domains:
conn = httplib.HTTPConnection(domain)
conn.request('GET', '/')
resp = conn.getresponse()
print 'Code %r from %r' % (resp.status, domain)
this will show you such codes as 301 (moved permanently) and 302 (moved temporarily); higher level libraries such as urllib2 would handle such things "behind the scenes" for you, which is handy but makes it harder for you to take control with simplicity (you'd have to install your own "url opener" objects, etc).
In App Engine, you're probably better off using urlfetch, which returns a response object with a status_code attribute. If that attribute is 401, it means that you need to repeat the fetch with the appropriate kind of authorization information in the headers.
However, App Engine now also supports urllib2, so if you're comfortable with using this higher level of abstraction you could delegate the work to it. See here for a tutorial on how to delegate basic authentication to urllib2, and here for a more general tutorial on how basic authentication works (I believe that understanding what's going on at the lower layer of abstraction helps you even if you're using the higher layer!-).

Unless I don't understand fully your question, you can grab the return code from the Response Object using the status_code property.
First, you'll have to issue a fetch() to the URL you want to test.

Most user-oriented sites don't use HTTP authentication, preferring instead to use cookie-based authentication, with HTML forms for signin. If you want to duplicate this in your own code, you need to make an HTTP POST request to the login URL for the application in question, and capture the cookie that's sent back, including that in all your future requests to authenticate yourself. Without more details about the specific site you're trying to authenticate against, it's difficult to be more specific.

You are not getting 401 because that site is not returning 401 but 200 always. Usually type of coding we do for websites is return 200 with a page saying "Please login..blah blah", if site returned anything other then 200 browser will not display the funky error msg.
So in short as i mentioned in other question, you need to look into login page, see what params it uses e.g login=xxx, password=yyy, post it to that page and you will have to manage the cookies too, that is where library like twill etc come into picture.

Related

Django and react login with google authentication

I was trying set up google authentication with react frontend and django rest framework backend. I set up both the frontend and backend using this two part tutorial, PART1 & PART2. When I try to login with google in the frontend I get POST http://127.0.0.1:8000/google-login/ 400 (Bad Request) I think it's because my google api needs an access token and an authorization code to be passed. After debugging the react js, I noticed the response I get from google doesn't have an authorization code. I suspect because responseType is permission(by default), Source:React login props , instead of code. I was wondering how would you change the response type in react? (I'm not even sure if this alone is the issue)
Here's my backend code
In my views.py file
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
callback_url = "http://localhost:3000"
client_class = OAuth2Client
in my urls.py
path('google-login/', GoogleLogin.as_view(), name='google-login'),
for my front end
/Components/login.js
const googleLogin = async (accesstoken,code) => {
console.log(accesstoken)
let res = await cacaDB.post(
`google-login/`,
{
access_token: accesstoken,
code: code
}
);
console.log(res);
return await res.status;
};
const responseGoogle = (response) => {
console.log(response.code);
googleLogin(response.accessToken, response.code);
}
return(
<div className="App">
<h1>LOGIN WITH GOOGLE</h1>
<GoogleLogin
clientId="client_id"
buttonText="LOGIN WITH GOOGLE"
onSuccess={responseGoogle}
onFailure={responseGoogle}
/>
</div>
)
I want to save the user in the database and have them stay logged in, in the front end.
This Post explains the login flow behind the scene. Here's Login flow image I'm basically stuck on returning code and accesstoken(I can return this successfully) step.
Here's my list of questions,
How do I return code from google?
I have knox token set up, can I
use it instead of the JWT tokens?
Does the class GoogleLogin(SocialLoginView), take care of the steps of validating the access token and code with google and creating the user with that email in database?
Would really appreciate your inputs.
After investigating a bit on my end, I think I might have a solution that works for you.
I've messed with OAuth before, and it's quite tricky sometimes because it has to be robust. So a bunch of security policies usually get in the way.
I'll provide my full step-by-step, since I was able to get it working, trying my best to match what you posted.
Firstly, to have a clean slate, I went off the example code linked in the tutorials. I cloned and built the project, and did the following:
Creating a new project on GCP
Configured the OAuth consent screen
I set the User type to "internal". This options may not be available if you're not using an account under GSuite (which I am). "External" should be fine though, just that "internal" is the easiest to test.
Created a OAuth 2.0 Client
Added http://localhost:3000 to the "Authorized JavaScript origins" and "Authorized redirect URIs" sections
Register a Django superuser
Registered a Site, with value of localhost:8000 for both fields.
Went into the admin panel, and added a Social Application with Client ID and Secret Key as the "Client ID" and "Client Secret" from GCP, respectively. I also picked the localhost site that we added earlier and added it to the right hand box. (I left Key blank)
Example of my Application Page
Filled in the clientId field in App.js, in the params of the GoogleLogin component.
Here's where I ran into a bit of trouble, but this is good news as I was able to reproduce your error! Looking at the request in the network inspector, I see that for me, no body was passed, which is clearly the direct cause of the error. But looking at App#responseGoogle(response), it clearly should pass a token of some sort, because we see the line googleLogin(response.accessToken).
So what is happening is that accounts.google.com is NOT returning a proper response, so something is happening on their end, and we get an invalid response, but we fail silently because javascript is javascript.
After examining the response that Google gave back, I found this related SO post that allowed me to fix the issue, and interestingly, the solution to it was quite simple: Clear your cache. I'll be honest, I'm not exactly sure why this works, but I suspect it has something to do with the fact that development is on your local machine (localhost/127.0.0.1 difference, perhaps?).
You can also try to access your site via incognito mode, or another browser, which also worked for me.
I have knox token set up, can I use it instead of the JWT tokens?
I don't think I have enough knowledge to properly answer this, but my preliminary research suggests no. AFAIK, you should just store the token that Google gives you, as the token itself is what you'll use to authenticate. It seems that Knox replaces Django's TokenAuthentication, which means that Knox is in charge of generating the token. If you're offloading the login work to Google, I don't see how you could leverage something like Knox. However, I could be very wrong.
Does the class GoogleLogin(SocialLoginView), take care of the steps of validating the access token and code with google and creating the user with that email in database?
I believe so. After successfully authenticating with Google (and it calls the backend endpoint correctly), it seems to create a "Social Account" model. An example of what it created for me is below. It retrieved all this information (like my name) from Google.
Example of my "Social Accounts" page
As for how to retrieve the login from the browser's local storage, I have no idea. I see no evidence of a cookie, so it must be storing it somewhere else, or you might have to set that up yourself (with React Providers, Services, or even Redux.

How to create custom URL in apex to get Json response from third party application

I am sending some perameters to the third party application using rest api In one of the perameter I am sending A URL, This URL will use by third party application to send a json response after 5 or 10 min. My question is how may i create that URL for third party app that they will use to send the response.
If the 3rd party can send HTTP headers too you could send to them the current user's session id. If that user is API enabled (checkbox in profile/permission set) - you could write an Apex REST service that accepts POSTs. They'd call it with Authorization: Bearer <session id here> and it could work very nice. This trailhead might be a good start for you. (or can you contact their developers and maybe agree to make a dedicated user in SF for them so they'd log in under their own credentials and send it back?)
If they cannot send any special headers (it'd have to be unauthenticated connection to SF) - maybe you could make a Visualforce page, expose it as Site and then page's controller can do whatever you need. Maybe you already have something public facing (community?), maybe it'd be totally new... Check https://developer.salesforce.com/docs/atlas.en-us.206.0.salesforce_platform_portal_implementation_guide.meta/salesforce_platform_portal_implementation_guide/sites_overview.htm
If none of these work for you - does the url have to ping back to Salesforce. Maybe you have control over another server that can accept unauthenticated requests like that and have that one then call SF. Bit like a proxy. You could even set something up fairly easily on Heroku.
Last but not least. This would be extremely stupid but if all else fails - in a sandbox enable Web-to-Case or Web-to-Lead and experiment with these. At the end of the day they give you an url you can POST to and pass a form with data. I think it'd have to be Content-Type: application/x-www-form-urlencoded and if you mentioned JSON they're likely to send it as application/json so might not work. If it works - you could maybe save the payload in Description field of Cases (special record type maybe?) and do something with it. I'm seriously not a fan of this.

App Engine different response on browser vs postman

I have a nodejs express server running on app engine.
If i make a GET request to https://astral-pursuit-252600.appspot.com/users in the browser it works fine to say unauthorized (401).
If I do the same GET request in postman it returns 400 bad request.
Is there any obvious reason why this is occurring?
This is a known issue with postman. This tool sends certain headers by default that you cannot remove. App Engine does not like them for some reason. I had to use the Insomnia tool instead which does not include default headers.
The first thing that I can think about is that, in order to do an API call, you need to use an API key in your request. You should create one, after that you need to obtain an access token. Your requests should be send to an address like https://astral-pursuit-252600.appspot.com/users?key=YOUR_API_KEY and include in your request a header to contain the access token. Something like this : --header 'authorization: Bearer YOUR_ACCESS_TOKEN'.
In order to do that I do not think you need to change manually each request, but you need to change some POSTMAN settings. You can find here a guide with exactly what setting should be changed for this use case.
You can see more details about this topic and a more detailed guide for doing an API calls here.
In case this was not the issue, could you please provide me your POSTMAN settings? I am pretty sure this is about the way POSTMAN does the requests anyway.

How to protect my api call from CSRF attack

I am working on angular js app,and tried to make a simple login page and tried to request my server API for authenticate my login call.Here what and how i planned to do.
Note: I am assuming that server is responsible for validating my token and request.
Provide username password to server via API call.
On getting authenticated the server will generate a token for my App(through which i made a call).
I stored this in my browser's COOKIE.
This Cookie (auth token) will be further used by app to to make each and every HTTP call to API.
Now this approach is working fine for me,but I believe it is openly available for CSRF attack.
In order to avoid the CSRF attack from my browser,i provide APP id or (version id) to my code which also travel with cookie to the API for http call.
The idea behind using this version id or App id,is this can be treated as a signature of my code,ie request is coming from the signed (verified) app who has alloted token=cookie value.
i just want to know how better my approach is and how much secure it is for my basic app point of view and for my major (wide project) app.
Here i am trying to show via a rough diagram
apologies for this tiny view and bad handwriting of the diagram.
Backend frameworks like Laravel have this pretty built in: csrf-protection.
You can pass the token to Angular by using angular's constant function: $provide#constant.
So after you initialize your app you could say: angular.module('myApp').constant('<?php echo csrf_token(); ?>'); and Laravel would do the rest. If you would want to implement a technique like this yourself, you should look into Laravel's source code: https://github.com/laravel/framework/blob/a1dc78820d2dbf207dbdf0f7075f17f7021c4ee8/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php.
Adding App ID + Version ID to each request won't protect your system from a CSRF attack, unless these are in a custom header - and if they are you might as well just use X-Requested-With because any non standard header is protected going cross domain, provided you haven't enabled CORS with an open policy.
The reason that checking App ID + Version if set in the query string or POST data is that the attacker can readily gain this information to add the App ID + Version ID to their cross site requests. Another method that would work for you is the Double Submit Cookies technique. Generate a random 128 bit string using a CSPRNG and then set this as a cookie value (e.g. CSRFCookie). On each request to your API, also pass this value. e.g. in the query string: CSRFCookie=<generated value>. On the server side you simply check that the values match. An attacker does not know the cookie value, therefore they cannot add the same value to the query string.
This method does have some minor vulnerabilities, only really exploitable in a MITM scenario or if you do not control all subdomains. Short answer: Use HTTPS only for all your subdomains and implement HSTS.

What is the OAuth scope for the Google Translation API?

Surely someone else is using the API, I've looked and searched, I cannot seem to find the correct value to place for the scope parameter when authenticating:
I've looked at all these scope lists, nothing, tried the OAuth 2.0 playground, translation is not there.
oauth playground v1
oauth playground v2
oath supported scopes
auth scopes
Any clues welcomed, thank you.
Error message:
Error: invalid_request
Missing required parameter: scope
Learn more
Request Details
Update
User Ezra explained that OAuth2 authentication is not needed for the Translation API.
I got down this road by this path:
I was trying to make the sample code here work:
translation api sample code
And didn't have the apiclient.discovery module
from apiclient.discovery import build
I went off looking for that which landed me here to this quick-start configurator
which gave me an autogenerated translation api project here:
This starter project which is supposed to be tailored for Translation API includes a whole bunch of OAuth configuration and so I wound up asking the question because of the error mentioned here
exception calling translation api: <HttpError 400 when requesting https://www.googleapis.com/language/translate/v2?q=zebra&source=en&alt=json&target=fr&key=MYSECRETKEYWENTHERE returned "Bad Request">
The code I'm using to make said call which errors out in this way is:
service = build('translate', 'v2',
developerKey='MYSECRETKEYWENTHERE')
result = service.translations().list(
source='en',
target=lang,
q='zebra'
).execute()
If I make the same call directly that the error complains about, it works ok
https://www.googleapis.com/language/translate/v2?key=MYSECRETKEYWENTHERE&q=zebra&target=fr&alt=json&source=en
Updated Again
Okay, I removed all the OAuth code from the sample project and then ran it again and then finally noticed that I had a typo in my secret key... donk
Thanks for the answers!
.
Thank you
I think you are misunderstanding what OAuth scopes are for. You didn't list any of your code, so I'm going to explain some concepts, and hope that you can apply them to your situation.
OAuth Scopes explained:
The purpose of OAuth scopes is accessing information about authenticated users. The scopes are different for each applications, and determine what information about a user that an application is granted access to.
Concretely, an OAuth request with the scope parameter as
https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile
Would show the user a prompt similar to the following when logging in:
+ View basic information about your account
* View your name, public profile URL, and photo
* View your gender and birthdate
* View your country, language, and timezone
+ View your email address
* View the email address associated with your account
While one with only https://www.googleapis.com/auth/userinfo.email would show something like:
+ View your email address
* View the email address associated with your account
Translate API explained:
To use the Translate API, you don't have to have users authenticated with OAuth. You simply get an API Key, and provide that key in your request to the service.
The use of the Translate API is completely orthogonal to the use of OAuth.
As documented on the Translate API site, to translate something you simply make a request to
https://www.googleapis.com/language/translate/v2?parameters
with the appropriate parameters.
The parameters needed are, as listed in the documentation, the
API key. Use the key query parameter to identify your application.
Target language. Use the target query parameter to specify the language you want to translate into.
Source text string. Use the q query parameter to identify the string to translate.
Concretely, a request to translate the text "hello world" into German would be:
https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&q=Hello%20world
Look at the parameters specification to get an idea of what you have to supply.
What to do:
Look at the source of the Python example using the Translate API or look up the API library for the language you want to use.
You'll see in the examples that there is no mention of OAuth scopes, because it's not needed to authenticate against the Translate API service. You only need to provide your API key, and the text to be translated in your request to the service.
There may be API calls that require scope, but Translate is not one of them.
If there is some piece of information about a user that you need, you will have to look up the API and Scope needed to access that piece of information. You will then supply this information to the Translate API as necessary.
In case of 400:
If you are getting an error response, that's good, because the call to the service is working, even if it's not doing what you want.
In the case of a 400, the Translate API's response will give you a clue about your error in its response.
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "keyInvalid",
"message": "Bad Request"
}
],
"code": 400,
"message": "Bad Request"
}
}
The response above indicates that the key is invalid. You can request a new one (or find out your old one) through the Google API Console.
Summary:
OAuth scopes are used for requesting information about a user. You will have to identify the scope when authenticating the user, and you will have access to all information provided by those scopes.
The Translate API doesn't need a scope. You provide an API Key (and some other information) in your request, and it gives back the translation as documented.
If there is information about a user that you wish to translate, it must be done in two steps. First, collect the information by authenticating the user in the appropriate scope, and second by providing that information to the Translate API.
If you're getting a 400, the response will include some information you can use to debug the problem.
According to Google's documentation, you have to look at the documentation for your specific API.
Update as per this Google Group question:
"The Translate API (both v1 and v2) is an unauthenticated API, so you don't need to use OAuth with it. Instead, for v2, you should use an API key, which you can get here: http://code.google.com/apis/console"
For error message
Error: invalid_request
Missing required parameter: scope
You need to add scopes in your form
<input type="hidden" name="scope" value="https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo#email https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/tasks https://www-opensocial.googleusercontent.com/api/people https://www.googleapis.com/auth/plus.login" />
Please refer spring social login with linkedin,facebook,twitter and google providers.

Resources