Login and logout in Node.js using authentication token - javascript

I'm working in Node.js Application. it requires login, logout ,and sign up functionalities I was thinking in creating the authentication using token based instead of cookies. and this will be the workflow
Send POST /login to the server to check if the user exist or not
if user exist I will send the token in JSON object and store it in the browser local storage
Now I want to redirect to home page after storing the token using window.location = "/"but I need to insert the token in the header and this my problem I found that's possible in angular using $httpProvider.interceptors that will intercept every request and set its header.
Is there any way that I can do that without angular?

This is normally good concept when using an API and then a web app in front of it.
Basically you have to save your token and send it with every request, if you have it.
What I normally do is when I do the /login I store the token in the localStorage of the browser, you can use this library to use it https://github.com/julien-maurel/jQuery-Storage-API
Once you have the token in your localStorage, when you do a call to the API you check if there's the token in the localStorage, if there's add a header.
Here's an example using jQuery ajax:
$.ajax({
url: '/data',
headers: {
'Authorization':'Bearer ' + localStorage.get('token')
},
method: 'POST',
dataType: 'json',
data: {},
success: function(data){
console.log('succes: '+data);
}
});

Related

Django doesn't receive cookies from request

I'm working on a Nuxt/Vue app that uses Django on the backend. I'm using the standard Django Session authentication. The problem with my code is that the user's are always logged out, according to Django, because Django doesn't see any cookie in the request.
Basically i created an API endpoin that should return whether or not the user is authenticated, but since Django doesn't see any sessionid cookie in the request, the user will always be unauthenticated to the backend.
def checkAuth(request):
print(request.COOKIES)
response = {'state': str(request.user.is_authenticated), 'username': str(request.user)}
return JsonResponse(response, safe=False)
If i print request.COOKIES it returns {}.
Here is how i send the request from the frontend, where i'm using Axios:
return axios({
method: 'get',
url: 'http://127.0.0.1:8000/checkAuth',
withCredentials: true,
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log(error)
});
The problem should not be from the frontend, since on Chrome i can see the session cookie and the csrf cookie correctly. I already tried to disable any possible CORS security setting on Django. The frontend is running on 127.0.0.1:3000 and the Django app on 127.0.0.1:8000.
Why doesn't Django see the cookies? Any kind of advice is appreciated

Make the browser open links with authorization header

I can use JavaScript to construct custom requests using my token, jQuery example
$.ajax({
url: "/page",
type: 'GET',
headers: {"Authorization": 'Bearer ' + localStorage.getItem('token')}
});
To get the page at /page which may require authentication to do.
But what if I have in my page a link
The user is already authenticated, there is a token in localStorage.
How can I set it up so that clicking on the link loads a new webpage as usual, but tell the server Authorization: Bearer ... in the header of that request so the server knows the request is authentic?
You can't specify headers in browser navigation. If you need to authenticate when the user visits the page, you should create a cookie.
Cookies get sent in all requests. Storing your authentication token there would do what you need.

How to send token in every request without using cookies or service worker?

I am trying to develop a web application using play framework 2.5 and jquery. I have got a use case where I cannot use cookies or service worker, but I need to send token in every request. I can generate a session_token for every user session and i can store that session_token in local storage.
Is there a way to intercept all types of requests and attach token in the request header? Requests which include opening a new webpage (window.location.href) or ajax request or form-submits or any redirects.
You can send your authentication payload simply in your request header like this
$.ajax({
url: 'YOUR_ENDPOINT',
headers: { 'x-my-custom-header': 'some value' }
});
Yes, try this code down below and it should intercept each request and attach an authentication header to it.
jQuery(document).ready(function(){
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', YourToken);
return true;
}
});
}
Make sure the code is wrapped up inside the jQuery(document).ready() as mentioned above. Please let me know if that works out for you.
check proxy object if you are using Javascript ES6.
Storing your token in local storage is subject to XSS attacks. Using service worker is one of the secure solutions when your javascript is dealing with such tokens.

JWT token with AJAX, non-AJAX, JQuery

I'm a bit frustrated with managing my JWT token during login, submits and redirects. Before I get started here's my technology stack just in case:
JQuery/Html -> Node.Js -> Java Restful Services -> MySQL.
My java Restful services manages creating the JWT Token returning it to the Node.js layer which decides what to do with it and pass it on the the client. This all works wonderfully.
To get the JWT token I'm making an ajax based authentication request to the Node middle tier, which authenticates and returns the token which is summarily crammed into localstorage on the client.
Now I have no desire what so ever to make the entire site load off a single page through ajax, it's a complex site and doing that is just dumb! I need to forward and navigate to sub pages while carrying along the JWT token.
Here's the question (finally)... How do send along the JWT token to the middle tier (node.js) without attaching it as a request or post parameter because that's a big no no? I can't seem to find a way to stuff it in the header associated with Bearer.
You need to store the token at client side using for example a cookie or localStorage
Ajax requests
Cookies: A cookie is sent automatically when making a request to the server, so you do not need to add a specific header
LocalStorage:It is needed to provide the token in each request using an HTTP header.
For example
POST /authenticatedService
Host: example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
This is an example code to show how to execute an ajax POST request using jquery
$.ajax({
type: "POST", //GET, POST, PUT
url: '/authenticatedService' //the url to call
data: yourData, //Data sent to server
contentType: contentType,
beforeSend: function (xhr) { //Include the bearer token in header
xhr.setRequestHeader("Authorization", 'Bearer '+ jwt);
}
}).done(function (response) {
//Response ok. process reuslt
}).fail(function (err) {
//Error during request
});
Form submit
With a form submission you can not control the headers set by browser, so it is not possible to set the Authorization header with a Bearer token. In this case you can
Cookie: store the JWT in a cookie that will be sent with the form data. You will need to add extra security to avoid CSRF attachs
Form param: The JWT is stored in a hidden field of the form.
Use always POST (not GET) to avoid cache of JWT
Link
A link executes a GET request. You could build the link adding the JWT as a query param url?jwt=...
But, consider in this case the security risks. Browser can cache the url and it will be present in logs. An attacker could potentially obtain them if he has access. Also the user could copy the link and use it outside your web application (e.g send it by email...)
If you use cookies, the token will be automatically sent to the server by clicking on the link, but this will only work if the user is authenticated. In this case be aware of CSRF vulnerabilities
Your only option is to store the token in a cookie if you don't want to do anything suggested above. You can't set http headers in links.

Flickr API OAuth Access Token request and Access-Control-Allow-Origin

Context
I'm trying to get an Access Token from the Flickr API using their their OAuth specification.
The first step to get an Access Token is to obtain a Request Token. I successfully manage to generate a correctly signed and valid URL to request this token: when I copy/paste the generated URL in my browser, I get the correct response.
Problem
As this part doesn't concern the user, I'm trying to get the Request Token by making a simple Ajax call:
console.log(baseURL + "?" + requestURL);
// When I copy/paste the log result in my browser, it works.
$.ajax({
url: baseURL,
type: 'GET',
data: requestURL,
done: function(data) {
console.log('Request Token data', data);
}
});
The problem is that I get an Access-Control-Allow-Origin issue:
XMLHttpRequest cannot load http://www.flickr.com/...
Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin.
I've tried using dataType: 'jsonp' as a parameter of the Ajax call without any success:
GET http://www.flickr.com/... 401 (Unauthorized)
Any ideas? Thank you very much in advance for your help!
It is not possible to implement Oauth 1.0 through just javascript without any server side script. Since the flickr's new authentication process is based on Oauth 1.0a. You got to use a server-side script.

Categories

Resources