I'm in a dead end, because I know that Javascript isn't made for synchronous work, and specially not AngularJS. However, I am in a situation where I am stuck needing it.
I have one main page on the domain "www" (with AngularJS), that calls "api" a lot. Some of the resources on "api" requires authentication, so it returns an 401, which in turn AngularJS picks up and displays a login-box when it sees.
The www-login supports a bunch of login methods and sends the password/oauth/whatever to the "api", which returns a token which the angular app stores in a cookie, and sets in $http.defaults.headers.common['Authorization'] so it can be used to authenticate furter requests to the api.
The same method is also used to get the username that belongs to the api-token.
This works perfectly and solves my design goals. But if the browser is going to an url that requires authentication, the 401 (and hence the login box pops-up). This is (I guess) because angular is not able to populate the Authorization field in the header before the 401 hits the browser..
Solutions?
Have an async=false request using jquery?
Close the login-box when we are done getting the data we want. The login box might flicker...
Store more meta-data about the login (ie, username) in cookies, so we dont haveto do get this information from the server when the app is loading.
??
Is there a better solution? This one time, for this one request, I want async=false in my Angular resource....
The solution I went for (which works perfectly) is to set $http.defaults.headers.common['Authorization'] = 'Token ' + old_api_token;, before the async request. And then overwrite it when the async request is done (if it have changed).
Related
I am trying to set up authentication and http sender script for Open API scanning project.
At some point in time I have reached a state where authentication script for oauth2 is working correctly (produces valid token obtained from remote endpoint) and http_sender appends authorization header for requests. It turned out later that I mistyped required header so I changed it's name, saved the script and rerun the script (via scan). Turned out now both headers are appended to outgoing http requests: mistyped version and correct one. Behavior does not change after restarting ZAP and reloading session, but mistyped header disappears when I create a new session, I can't find where can I clean it up and it does not look right to recreate session when one minor change is needed in the script.
The second issue that I have is that authentication script just stopped working without any modifications to it. I switch between environments occasionally but code remains the same. I even moved hardcoded values from context to script and it still does not work. I have set up a parallel script in python to fetch the token and it works (all parameters being the same), but in ZAP I get authentication failure (recreating session does not help). I don't own the oauth endpoint so it's not possible for me to take a look at it directly, but I suspect that both problems have something in common. Looks like some data is residing in the shadows and affects how the scripts are run.
First version of sender script:
function sendingRequest(msg, initiator, helper) {
var loginToken = org.zaproxy.zap.extension.script.ScriptVars.getGlobalVar("logintoken");
msg.getRequestHeader().setHeader("Autentication", "Bearer " + loginToken);
}
Second version of sender script:
function sendingRequest(msg, initiator, helper) {
var loginToken = org.zaproxy.zap.extension.script.ScriptVars.getGlobalVar("logintoken");
msg.getRequestHeader().setHeader("Authorization", "Bearer " + loginToken);
}```
Authentication function is just tuned version of the zap template to send oauth2 parameters in the body of the POST request and actually worked for some time. It would really help to have some troubleshooting capabilities during scripting.
Re the first issue, it all depends on how the script is being used. The ZAP session is a record of all of the requests and responses. For some of the old responses you used the wrong header. That hapenned, you cant take it back. If you reuse those requests then ZAP will send the wrong header unless you remove it. If you create new requests that are not based on historic ones then the header should not be present.
Re the second issue, authentication is hard and can fail for what seems like minor differences :( One good option would be to proxy your python script through ZAP. Hopefully it will still work, and then you can compare the working request with the failing one.
Previous posts — 1 , 2
What I have now: AngularJS app with two controllers. First works with CouchDB documents and the second perform sign-in requests to example.com/demo/_session.
When I open application, I can't do editing with couchdb (in first controller), because some actions I've limited to logged users only. In second controller I'm sending simple POST over $http, which return Http-only (so no cookie magic there) auth cookie AuthSession. That cookie bound to couchdb address and in theory any request from page to couchdb address must contain that cookie also.
But this no happens. No one call to couchdb, except calls to /_session comes with AuthSession cookie. E.g. example.com/demo/_session getting with AuthSession and example.com/demo/records not.
In learning Angular and CouchDB I came to deadlock.
What I'm doing wrong? I do not want to hide couchdb behind something with custom auth — too complex and not a good way, I think.
UPD: Getting Set-Cookie header also fails — it not available in HttpPromise.success(function (data, status, headers, config)) headers. I'm tried to get it like headers("Set-Cookie") — no luck.
Maybe something wrong in couchdb configuration? I've uploaded it to pastebin.
Check CORS to be enabled (* in my cause)
Check cors/credentials in config, it must be true
Use {withCredentials:true} in Angular $http
Now it works.
I need to retrieve a facebook page's list of posts (feed) using their javascript SDK, just like they explain in their docs: https://developers.facebook.com/docs/graph-api/reference/v2.4/page/feed
/* make the API call */
FB.api(
"/{page-id}/posts",
function (response) {
if (response && !response.error) {
/* handle the result */
}
}
);
I need it to be my website's "news section", so users should see it even if they are not connected to facebook.
The problem
Cool, but there is a problem... It returns: An access token is required to request this resource.
Holy cow... I'd like to get some access token for you #facebook, but my app doesn't make use of your authentication tools/plugins.
ANYWAY, I tried with FB.getLoginStatus(); but doesn't work, because the only way it can return an access_token is if the user is actually connected to the application. My users may not even be logged to facebook!
So, ¿How can I get an access_token to be stored into a variable, and later be used to get /{my-page}/posts?
I've already payed a look to this SO question, but it doesn't solves my problem, simply because there are no such "generic tokens".
I've also read https://developers.facebook.com/docs/facebook-login/access-tokens/ and that also relies on tokens generated through facebook login methods... So, can't I display a list of fb page's posts in my website, without being connected into facebook, hence an application?
ADD: My app is build with angularJS, I'm not dealing with server-side code. I shall rely purely on javascript methods.
You could either use an page or an app access token, but as you'd be using them on the client-side, neither of them are an option.
See
https://developers.facebook.com/docs/facebook-login/access-tokens#apptokens
https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens
Note that because this request uses your app secret, it must never be made in client-side code or in an app binary that could be decompiled. It is important that your app secret is never shared with anyone. Therefore, this API call should only be made using server-side code.
I'd strongly recommend to build a simple server-side script (PHP for example) to proxy the request to the Graph API. You could then call this via AJAX for example and load the posts asynchronously (and alse get rid of the FB JS SDK!). There is NO way to handle this in a secure manner if you don't want to use FB Login for all of your users (which also doesn't make much sense IMHO).
I think it's straightforward :)
Since pages' posts are always public, it only needs a valid access token to retrieve page posts.
Quoting what you've written:
So, ¿How can I get an access_token to be stored into a variable, and later be used to get /{my-page}/posts?
You only require an access token.
My suggestion would be;
- Generate an access token for yourself (no extra permission needed)
- request page-id/posts
This way you don't require other users to be connected to facebook, you can simply requests page-id/posts to retrieve posts with access token you generated for yourself.
I hope it solves your problem :D
TIP: As long as posts are public, you only require a valid access token, it doesn't need to be user or page specific.
I'm trying to think on approach to do authentication with Angular and remote server. Usually what I do in local server, like what they did in MEAN.IO, check if has user and if it is I put it on the global window and that's how I know that user is authenticated.
for example in laravel:
#if(Auth::check())
<script>
var user= [[[Auth::user()]]]
</script>
#endif
and it survive refresh because im check it at run time too.
but now the server is remotely and i have to do something like get request to some url /getUser. But thats not good since all the AngularJS
components will have to wait for the response to return causing inconsistencies and
development overhead.
So what I should do?
You can use "resolve" in order to avoid changing your current logic.
Define a Security service that performs the check let's say Security.getUser() and add it to the resolve of each route you need to secure. That way, your controller will be loaded only once the user is already checked. In case the server will return an authentication error, redirect to the login screen.
You can check out my slides from a secured angular talk I gave goo.gl/kMvoFj
or go over my github repository (It's still very raw, but the main idea is there) ng-secure, I think it might help you.
I wrote an Android app that should 'connect' to a (private) forum using HTTP GET (and sometimes POST) requests. The basic idea is as such:
Login page where users submit their credentials. Login is performed by doing a HTTP POST (tried GET too, same result) to the Login page of the forum, with their username and password as the parameters. The request should return some cookies that I store in a BasicCookieStore.
Every page of the forum they want to visit is retrieved using HTTP GET. I parse the HTML source that I obtain and show them only the relevant info. In order to authenticate the users, the same BasicCookieStore that I used for login (step 1) is set as the cookiestore for the HttpClient.
This method has been working all the time during my testing, and has worked for my beta testers too. Now that I released the app, it became apparent that many users were having issues, especially on mobile connections (Wifi seems to be no problem).
By logging the HTML source that was returned in all the HTTP GET requests, I have a strong suspicion that the actual login works fine, but somehow the cookies don't get returned or stored or something in that direction. The problem is that the HTML source of the first page they will receive should be the list of forums. In the case of users with problems however, they get served a page that basically reads "You must enable Javascript to view this page".
The strange thing is, I don't receive that page when testing, nor do many of my users. Even worse: some users are now reporting it worked fine for them for days or weeks, and has now stopped working. Others have the exact opposite: not working for days, suddenly working now. One user has reported he was in Greece for 2 weeks, where it worked flawlessly, then he got back to Germany, and it stopped working again.
There seems to be a random component at play here.
I have tried various things, mostly with the way I do the HTTP GET requests. I started out using the normal DefaultHttpClient, with various settings, such as this:
HttpClient httpClient = new DefaultHttpClient();
// Define parameters
HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT);
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
// Set cookiestore (getCookieStore returns the same cookiestore)
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, getCookieStore());
HttpGet http = new HttpGet(url);
http.addHeader("Accept", ACCEPT_STRING);
http.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
// Execute
HttpResponse response = httpClient.execute(http, localContext);
//... Process result (omitted)
Now I have switched to using AndroidHttpClient instead, with the rest of the code basically unchanged, and seem to get the same result.
I have also tried using the AsyncHttpClient library, which works quite differently, but once again the same result. I tried using its PersistentCookieStore as well, and you guessed it - same result.
I am clueless at this point. Am I looking in the wrong direction? The fact that a website would respond with "you need to enable Javascript" for some users but not for all seems to indicate an issue with cookies. I don't know how a website determines if javascript is enabled, but surely with a HTTP GET request there is no javascript at play. So why do I (and many other users) get to the page without any problems, while others get the 'no javascript' message? The only reason I can think of is cookies, but I have no clue what the problem exactly is.
Any help would be much appreciated!
I doubt the problem is cookies. More likely is a network configuration problem.
For example, your user might have connected to a wifi hotspot with a captive portal page (which uses javascript to make you sign in before you can use the hotspot). In this case they should first open the browser, try to browse to (e.g.) http://google.com, get redirected, sign in, and then launch your app.
Or, your user might be connecting through a proxy. Many mobile carriers around the world will proxy their users' HTTP connections, sometimes doing horrible things to the content. Switching to HTTPS might help with that.