Programmatically getting the Authorization header for AJAX requests - javascript

I'm trying to work out my mobile data usage & I noticed there are simple APIs to query on https://secure.example.com/myaccountmgr/fapi/usage/data/... but they carry an Authorization: 0a60bd4e0blahlblahhash in order to query them.
I copied the curl commands when logging in, but it does a fairly complex redirection dance that I not sure how to get curl to compute since it's Javascript.
How do people do this? After further debugging I noticed that it later does a AJAX request via Angular to https://secure.example.com/myaccountmgr/fapi/login/esso where it returns a utoken which is used in the subsequent AJAX requests as the Authorization value. So what I am asking, is how do I view just this response once I log in, so I can grab the token?

Related

Is using a query string in POST request a bad practice?

There is a system that sends POST requests from frontend to backend. These POST requests do not use the body to pass the data to the server; instead, it uses query strings in the URL params.
These requests do not send files or JSON, only several string params.
W3C does not describe that situation https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
Is it a bad practice to use query strings for POST requests, and if there any negative consequences of using that from security or performance or architecture reasons?
Are there any conventions that define the usage of body or query strings for different types of requests?
Reminder: In 2014, RFC2616 was replaced by multiple RFCs (7230-7237).
Is using a query string in POST request a bad practice?
Not if you know what you are doing.
Mechanically, it is all fine: are we allowed to use POST with a target-uri that includes a query-part? Yes. Are we allowed to use POST with an empty request body? Yes. Are we allowed to do both of those things at the same time? Yes.
The hard part: will this POST request invalidate the correct representations from the cache?
Cache-invalidation happens when the server returns a non-error response to an unsafe request (POST is an unsafe request method). The representations that are invalidated are those that match the target-uri of the unsafe request.
GET /foo?a=b HTTP/2.0
POST /foo?a=b HTTP/2.0
Here, if the POST is successful, the representations cached after the successful GET request will be invalidated in the cache.
GET /foo HTTP/2.0
POST /foo?a=b HTTP/2.0
Here, the effective request-uri is not the same, which means that general purpose components won't invalidate the cached representations of /foo.
There's nothing wrong with using query parameters in a URL in a POST request, with or without a request body. If it makes semantic sense for your request, it's fine. The POST method in itself has a semantic meaning distinct from GET, it doesn't require a request body to be useful, and the URL is yet distinct from that again. A classic example might be:
POST /foo/bar?token=83q2fn2093c8jm203
I.e., passing some sort of token through the URL.
There's no general security problem here, since anyone who could intercept this POST request to read the URL could also read its body data; you'll hardly find an attacker in a position that allows them to read the URL but not the body. However, URLs are typically logged in server access logs and browser histories, while request bodies aren't; that may or may not be worth considering, depending on what information you're transporting in those parameters and who has access to those logs.

How to send DELETE request using browser in javascript

I have to use Postman to send POST PUT and DELETE request to my server, is there any way I can hit POST request through browsers directly, using browser front end only
I Have a form that on submits should delete data from my server but using a form I can send only the GET or POST method only I know I can do it with the POST method, but I need to do it by DELETE.
You may be able to send a "DELETE" request via Ajax, the question should be will your server understand it.
While DELETE is a http method, it's not a generally supported request type in most back-end frameworks, rather you generally "overload" a POST request while setting the action as delete via a hidden form field.
So depending on your back-end framework, you would need to consult their documentation, but generally its accomplished as described above.
As for performing a POST request by URL alone, in a browser there is no way that I'm aware of, you need some tool, to be able to set headers to be able to form a POST request, such as JavaScript, curl etc
MDN has a great introduction to the topic
The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

How to respond with HTML or JSON depending on the request in Sails.js

Let's say I have a model called User with its basic REST CRUD (GET, POST, DELETE, UPDATE).
When I go to user/4 (where 4 is an ID of a User that doesn't exist), there are two cases:
If I'm doing it with a REST client like Postman, I'd get a 404 and nothing else.
If I'm on the browser, I'll get a 404 page (with text, images, etc), which is defined in the views folder.
How can I achieve this for findOne, find, and other URLs? I want to be able to have JSON-only responses, and HTML pages responses for different types of requests. But I don't want to override the functions, because the ORM is already doing a lot of work that I don't want to lose.
EDIT: My solution would be to leave the API with a prefix, such as /api/user/4 and the HTML response without the prefix user/4, but I'd like to see more elegant solutions.
EDIT 2: I just decided to go all JSON, and use a REST service only with an independent front end ;)
If you have control over the headers sent by the API client, I see two clean semantic solutions, based on the headers sent :
you could rely on the X-Requested-With: XMLHttpRequest header to recognize Ajax queries
rely on a Accept: text/json header to explicitly request json
You could also modify the url with file extensions to request a specific response, user/4.html => send html, user/4 => send json.

Html vs JSP - get request header token value

I am working on Java application . Front end would be Angular2 .
If I try to open my application home page( index.html is configured in web.xml as default page ) . Access URL should be http://localhost:8080/MyWebApp .
Then I have taken into an standard organization's login page for authentication. If authentication succes , HTTP Authorization token will be set in the request header and finally control comes to display my application home page.
If I use jsp, I can get request header as,
String authHeader = request.getHeader("authorization");
out.println("<h2>HTTP Authorization header:</h2>");
if (authHeader == null) {
out.print("No authorization header");
} else {
out.print("<textarea readonly id='authHeader' rows=\"5\" cols=\"80\">" + authHeader + "</textarea>");
}
But we are using html as front end, because of angular 2 .
So for my scenario, how I can I get the request header and token.
Please don't hesitate to edit my question, if it is not clear.
You can't get a value of a header from client-side JavaScript. The only exceptions are the User-Agent and Referrer headers, because the browser provides the values in the document and navigator objects.
You said you are working on a Java application with an Angular 2 front end and some other application provides a token (might be useful to specify if this is something standard, e.g. OAuth2). I will assume that it is a custom token. I believe you also meant you have some server side component, a servlet.
What you can do is to implement the authentication using the servlets (or even JSPs) and then redirect back to the Angular 2 front end application, passing the token in the URL as a query parameter. URL is easy to read in Angular 2. However this is not very secure, even if you use something like JWT. As an alternative to URL, you can use the Set-Cookie header and then read the cookie from Angular.
What would be almost secure would be to authenticate the user using the server side (servlet or even JSP). Then create a one-time token which is passed in the URL as a query parameter when redirecting to your HTML page. Then use the one-time token in a call to the server again to retrieve the real authentication token using a proper REST call from Angular 2 with request and response.
Depends on how much control you have and what kind of authentication the auth application uses, you might want to take a look at the OAuth2. It deals with plenty of different authentication scenarios. Specifically the OAuth2 implicit grant flow is used to authenticate users from client-side only applications. Even if you can't use that, it will give you some ideas.
When you are using a server-side authorization, your server put headers with authorization to your HTML pages. But also you can put this tokens to your page response by meta tags at server side. And then access to meta tags by js.
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
Meta tags are similar to response headers and can complete or override response headers.
Read this post please Spring Security CSRF Token not working with AJAX call & form submit in same JSP
You can handle this at server side(JSP's expressions work on server side), create a handler method on server where you can check header and then redirect to your Angular App.
I think we can use HTTP HEAD method as JQUERY AJAX request in your HTML page .
https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
The HEAD method asks for a response identical to that of a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.
ajaxRequest = $.ajax({
type: "HEAD",
async: true,
url: 'index.jsp',
success: function(message){
var headerValue =ajaxRequest.getResponseHeader('Content-Length')]);
}
});
There are various way to solve this issue as I faced it a lot before and what I prefer is;
When authentication is completed in login page and a token generates I store it into HTML storage, make be in localStorage.
The main point you should understand that your views should not be accessed directly and there has to be a authentication (or may be a authorisation) step(s) before accessing the page(view).
So what you can do is set a URI for accessing any page, consider that is;
http://host/appname/pageName
And when you connect with this URI via ajax call add the token that is stored in localStorage in headers. And check all authentication and authorisation works and if success return the view(as the pageName suggested in the URI), else return the login view.
If i understand you correctly,
Angularjs is a client side framework and is intended to run inside a browser without any intervention of server by reducing its load by serving the application logic
All operations that need to be performed by angular will only be initiated at client side by the browser after loading the HTML and javascript.
The scope of angular is only limited to that area any way it is not a disadvantage it is the actual intention of client side frameworks.
Regarding request response headers you can only have access to headers of AJAX request
Following are the solutions to these problems:-
If you are using tomcat or any servelet container in order to serve the application or hosting angular code you can use JSP insted of HTML,since JSP is processed to html by the servelet container before passing it to client side.I think this solution will work in your case based on my inference form your question
Otherwise configure servelet that process the success and failure handlers from the authentication server and from angular you need to poll the servelet for getting the request header value.

How to POST data to an HTTP page from an HTTPS page

I know this is a long shot, but I figured I'd ask the question anyway.
I have an HTTPS page and am dynamically creating a form. I want to POST the form to an HTTP page. Is this possible without the browser popping up a warning? When I do this on IE8, I get the following message:
Do you want to view only the webpage content that was delivered securely?
Essentially, I'm asking about the inverse of question 1554237.
Sadly, I know of absolutely no way to not get warned when posting from HTTPS to HTTP. If you serve the form securely, the browser expects to submit the data securely as well. It would surprise the user if anything else was possible.
Nope, can't be done. Our good friend IE will always pop up that warning.
There is a way to do this if you write a back-end service of your own. So lets say you want to post an HTTP request to s1 using your front-end service fs1.
If you use Spring, you can use an ajax call from fs1 to a 'uri' that is recognized by your spring back-end, say bs1. Now, the service bs1 can make the call to the s1.
Pictorial representation here: http://i.stack.imgur.com/2lTxL.png
code:
$.ajax
({
type: "POST",
uri:/json/<methodName>
data: $('#Form').serialize(),
success: function(response)
{
//handle success here
},
error: function (errorResponse)
{
//handle failure here
}
})
You can solve this by either acting as a proxy for the form destination yourself (i.e. let the form submit to your server which in turn fires a normal HTTP request and returns the response), or to let access the page with the form by HTTP only.
If you don't need to actually redirect to the insecure page, you can provide a web service (authenticated) that fires off the request for you and returns the data.
For example:
From the authenticated page, you call doInsecure.action which you create as a web service over https. doInsecure.action then makes a manual POST request to the insecure page and outputs the response data.
You should be able to do this with the opensource project Forge, but it sounds like overkill. The Forge project provides a JavaScript interface (and XmlHttpRequest wrapper) that can do cross-domain requests. The underlying implementation uses Flash to enable cross-domain (including http <=> https) communication.
http://github.com/digitalbazaar/forge/blob/master/README
So you would load the Forge JavaScript and swf from your server over https and then do a Forge-based XmlHttpRequest over http to do the POST. This would save you from having to do any proxy work on the server, but again, it may be more work than just supporting the POST over https. Also, the assumption here is that there's nothing confidential in the form that is being posted.

Categories

Resources