How to send access token to server the most safest way with GET request? - javascript

I need to send access_token to my REST server...
How to send access token to server with GET request?
Is it safe to make request like: https://localhost:8443/docs/1?access_token=12345 ? I am using HTTPS.

As per the OAuth 2.0 standards, it is recommended to pass the Access Token as a bearer header.
Please check RFC 6759 for more information.

Related

Access and Refresh Tokens

I am using caspio rest api to authenticate my users in a mobile app. Upon authenticating, I was given an access token to which I included in my AJAX call under the parameter 'Authorization' : Bearer [access token].
I understand that I can renew the token with the refresh token given to me where I can use the POST call.
My question is: prior to using the POST call for a new token, must I store the access token?
Also, the Caspio website advised this format for the POST call:
Method: POST
URL: Token Endpoint
Body: grant_type=refresh_token&refresh_token= [token value]
Header parameters:
Authorization: Basic [string "Client_ID:Client_Secret" encoded in Base64]
Content-Type: application/x-www-form-urlencoded
Should I also include the client ID and client secret in the parameters? Upon using Firefox's rest client, I'm getting a bad request (400) error.
Thank you for the help!
I never using caspio rest api before. The answer base on my OAuth experiences.
My question is: prior to using the POST call for a new token, must I store the access token?
YES! The OAuth 2.0 using the access token to switch the refresh token at first time.
Should I also include the client ID and client secret in the parameters? Upon using Firefox's rest client, I'm getting a bad request (400) error.
According to the api document. You should include the client ID and client secret in your request, like most OAuth 2.0 do.
The bad request (400) error you may see the rfc6749 to find further information.

Setting Basic authorization details in request headers

In our application we validate user name/password. Once validation is done, credentials are encoded using base64 and then needs to be set at request header for subsequent rest calls.
Need to set below in request header.
Authorization:Basic AQNLzR69OFTNJE8X
In the response setting as below from the java code,
javax.ws.rs.core.Response.status(200).entity("").header("Authorization:","Basic AQNLzR69OFTNJE8X").build();
And in the javascript tried setting as below,
sessionStorage.setItem('Authorization:', 'Basic AQNLzR69OFTNJE8X');
But in the subsequent rest service calls in the same session can see the header request is not set with authorization. Request to provide some pointers on setting the Authorization in javascript, so that it is retained for the entire session.
I think you misunderstand how authentication works (or should work).
You are supposed to send the Authorization header only once during the authentication. If the authentication is successful, the server sends you back a session cookie and your session is marked as authenticated (server-side).
You never send back the content of the header, and you don't have to send it each request.
1) The Authorization header is not automatically added. But the cookie will be automatically sent.
2) You should not send the credential and return them: for security purposes, you want to transport them the less you can.
3) You don't want to store the credential in the sessionStorage, I don't know if this is a secure place for a password (i doubt it), but here, the password is only encoded in B64, and it's reversable. So it's as well as cleartext (which is bad for a password).
Hopes this helps!

Check access token before http request

I'm creating an app using Angular 1.5.8 and Laravel 5.2. I'm using a library by Luca Degasperi to create Token Based Auth
Via Angular I make a call and I receive access_token, TTL and refresh_token. I store access_token and refresh_token on localStorage. I can use access_token that I get to make calls to get some data from my API. When token expires I'm getting a message that the token is invalid with 401 code
So my question is how to check if the token is still valid before I send a http request to my API? What is the best way to refresh the token? Ok, I can send a request for the refresh my token to https://my.api/oauth?grant_type=refresh_token&refresh_token=f32j93201h00xpaf1, but how to check it before every http request? Can I repeat the call if the response code is 401? And how?
Please, give me some advice :)
I had exactly the same problem few days ago. Angular Error response interceptor is all you need ;) Also, this article was really helpful
You cannot. You have to check against a login. Therefore it's just a re-login.
I guess that if you get a 401, your refresh token is already done.
Though I guess that you can join that refresh token with all your requests? I might be wrong.
Ensure that your token TTL is always up to date by refreshing its TTL from time to time (like with requests to your API).
Can't you use the TTL to determine if the token is still active? When you store your tokens in local storage you can add the date/time the token was stored and each time you go to make a service call you can check the TTL against the time the token was stored.
It will only tell you when it expires, though, and not if the token was invalidated for some other reason.

How to store Access token value in javascript cookie and pass that token to Header using AJAX call

I have a login form, as shown below:
<form method="post" name="logForm" onsubmit="onLogin()" action="dashbooard.html">
<label>Email</label>
<input type="text" name="email">
<label>Password</label>
<input type="password" name="pass">
<input type="submit" name="submit" value="Login" >
</form>
Now when I click on the Login button, I am authenticated by the server and an access_token is generated and returned back to me via a REST API.
I would like to store that access_token in a cookie and pass that token into a request. But, I don't know how to do this. I would love to receive help on this.
Here is how you can use a cookie for your question regarding the access_token:
1. Storing the cookie on the client:
document.cookie='access_token=[value]' where [value] is the token value.
If we use a reader/writer library that MDN provides here, we can do the above as:
docCookies.setItem('access_token', [value]);
The reason why we would use something like this instead of the standard way is to make it easier to access and delete the token, as demonstrated in #3 below.
2. Passing the cookie back to the server:
We need to send the access_token back to the server through the header.
This should automatically be done for you, assuming that the server sends a response after authentication like Set-Cookie: access_token=[value].
If for any reason you encounter an issue regarding Access-Control-Allow-Origin, here is an example of how you can set Access-Control response headers for CORS:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Authorization
3. Deleting the cookie:
Using the reader/writer library linked in #1, we can do the following:
docCookies.removeItem('acccess_token');
Security considerations when using cookies for authorization:
XSS, MITM, and CSRF attack vectors should be considered when using cookies for authorization. On a basic level:
For XSS attacks, we can set the HttpOnly flag in the response header by the server to prevent a client side script from accessing the cookie.
For MITM attacks, we can use the Secure flag to guarantee the cookie is not sent over an unencrypted HTTP channel.
For CSRF attacks, the recommendation by OWASP is the Synchronizer Token Pattern. It's basically a randomly generated token that is sent by the server and is sent back by the client to verify a request submission done by the user.
Try this code
document.cookie="username=John Doe";
A more elaborated answer based on above answers, in the success part of your Ajax call.
success: function (json) {
// console.log(json); // log the returned json to the console
var access_token = json.token;
document.cookie="access_token="+access_token;
},

Google OAuth2 - Exchange Access Code For Token - not working

I am currently in the process of implementing a server-side OAuth2 flow in order to authorize my application.
The JS application will be displaying YouTube Analytics data on behalf of a registered CMS account to an end user (who own's a channel partnered with the CMS account). As a result of this, the authorization stage needs to be completely hidden from the user. I am attempting to authorize once, then use the 'permanent' authorization code to retrieve access tokens as and when they're needed.
I am able to successfully authorize, and retrieve an access code. The problem begins when i attempt to exchange the access code for a token.
The HTTP POST Request to achieve this needs to look like this...
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
I am using this code to achieve this:
var myPOSTRequest = new XMLHttpRequest();
myPOSTRequest.open('POST', 'https://accounts.google.com/o/oauth2/token', true);
myPOSTRequest.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
myPOSTRequest.send('code=' + myAuthCode + '&redirect_uri=http%3A%2F%2Flocalhost%2FCMSAuth3.html&client_id=626544306690-kn5m3vu0dcgb17au6m6pmr4giluf1cle.apps.googleusercontent.com&scope=&client_secret={my_client_secret}&grant_type=authorization_code');
I can successfully get a 200 OK response to this Request however no access token is returned, and myPOSTRequest.responseText returns an empty string.
I have played with Google's OAuth Playground - and can successfully get a token using my own credentials.
Am i missing something here?
You cannot do this, because there is the same origin policy. This is a security concept of modern browsers, which prevents javascript to get responses from another origin, than your site. This is an important concept, because it gives you the ability, to protect you against CSRF. So don't use the code authorization flow, use instead the token authorization flow.
Try and build up the full URL. Then dump it in a webbrowser. If its corect you will get the json back. You have the corect format.
https://accounts.google.com/o/oauth2/token?code=<myAuthCode>&redirect_uri=<FromGoogleAPIS>&client_id=<clientID>&client_secret={my_client_secret}&grant_type=authorization_code
Other things to check:
Make sure that you are using the same redirect_uri that is set up in google apis.
How are you getting the Authcode back? If you are riping it from the title of the page i have had issues with it not returning the full authcode in the title try checking the body of the page. This doesnt happen all the time. I just ocationally.

Categories