How to properly check authentication with Vue.js (Vue router) and Django - django

I am trying to check if a user is authenticated on protected routes in vue-router. I have Django rest framework that sets sessionid on login.
I have seen people using vuex or local storage to store session information. But, If the token was forcibly expired on the server-side a user will be allowed to navigate since localStorage still says IsAuthenticated=true. In this case, is it the best choice to make a request to the Django backend such as fetch("url/auth/authenticated")?

Please consider adding routing guard on protected routes.
Vue Router permits you to do stuff before entering any route.
The following docs get you covered. Do remember that your API response is what rules you front end. So for checking if a sessionid is still valid, you can create an endpoint to do that and when it respond with an expired state, your frontend should unset everything related to the session in your vuex store and from the local storage, then redirect the user to the connexion page!

Related

Is saving user's id and login token in local storage a good idea?

I am developing Django + React project and I'm caught with this security approach concerning login and managing views for the logged in user.
I am using django-rest-framework or DRF for my RESTful API. And I'm using django-rest-knox for authenticating user logins since I am implementing Token-based authentication (instead of session-based which uses CSRF).
Question: Is it a good idea to save user's id and token in local storage?
Currently, I have a /auth/login/ API endpoint that handles the backend logic of logging in user and returns JSON response of login details upon successful login (including user id and token).
In my frontend, I use redux and redux-persist so the user's login details are kept even when the site is refreshed. The way redux-persist do it is that it saves the response in local storage. This means that the user id and token can be accessed and changed anytime thru dev tools.
If user will then make a POST request to an API that requires a Token authentication header, the frontend will look into that local storage for the token value to be supplied to the request header.
If user will then make a POST request to an API where the user id is required in the request data, the frontend will also look for the id in the local storage.
Localstorage is not safe, especially for storing tokens and ids. Any user can go to the browser's developer tools, see and also edit its contents, for example.
You could check on Django's sessions, so you can store data securely at server side and keep its contents associated with a specific user. There is a great tutorial at Mozilla that explains sessions in a clearer way than the official documentation.

can I use session cookie instead of csrf?

I have been reading about csrf and fiddliN around with implementing it using go and gorilla toolkit. I am also using gorilla sessions which i have implemented to store a user id in an encrypted cookie.
the cookie is decrypted and i fetch the user from the db with the now unencrypted key-value store using a middleware I wrote...
if the user is creating the session cookie from authentication through an oauth2 provider, do i have any need to implement csrf protection if all the views that need such protection are only allowed to authed users anyway?
Suppose a user has logged into your site, and has continued to browse the Internet in the same session. They stumble across another site which is maliciously targeting yours, with HTML or JS that causes the user's browser to make a request to an endpoint on your site. This will contain the user's session cookie for your domain, and succeed unless protected by a CSRF token.

Using ember-simple-auth when the login page is on another system

The page to login to our application is a jsp hosted on another machine. I have managed to get requests firing to this machine by modifying authenticated-route-mixin by allowing window.location.replace to be called if the route start with http.
beforeModel(transition) {
if (!this.get('session.isAuthenticated')) {
Ember.assert('The route configured as Configuration.authenticationRoute cannot implement the AuthenticatedRouteMixin mixin as that leads to an infinite transitioning loop!', this.get('routeName') !== Configuration.authenticationRoute);
transition.abort();
this.set('session.attemptedTransition', transition);
debugger;
if (Configuration.authenticationRoute.startsWith('http')) {
window.location.replace(Configuration.authenticationRoute);
} else {
this.transitionTo(Configuration.authenticationRoute);
}
} else {
return this._super(...arguments);
}
}
This is working but when I am redirected back to my application, ember-simple-auth thinks I am no longer logged in and redirects be back to the remote machine, which then sends me back to the application in an infinite loop.
Obviously I need to set something to let ember-simple-auth know that it it is actually logged in. Why is it not doing this automatically? What am I doing wrong?
I am pretty new to oAuth so I could be missing some basic setting here.
Here is the URL.
ENV['ember-simple-auth'] = {
authenticationRoute: 'https://our-server.com/opensso/oauth2/authorize?client_id=test-client-1&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fsecure'
};
Instead of modifying the AuthenticatedRouteMixin, I'd recommend handling your app-specific login in an Authenticator-- the key configuration primitive that Ember Simple Auth provides as part of its public API.
To the best of my understanding, on first loading the app, and checking to see if a user is authenticated, Ember Simple Auth will use the restore method, defined as part of the Authenticator API.
You can return a promise from restore that resolves or rejects to indicate whether the user is authenticated. How you check this is an implementation detail of your auth system.
I don't know how you're storing credential(s) on the client (would be great if you could provide more detail), but here's an example flow, using cookies for authentication:
Ember boots, ESA attempts to restore the session.
restore makes a simple AJAX request to a secured, "dummy" resource on your Java server-- and checks if it gets back a 200 or a 401.
We get a 401 back. The user isn't authenticated, so reject in the Promise returned from restore.
Let ESA redirect the user to your authentication route. Ideally, don't override the AuthenticatedRouteMixin-- instead, use the beforeModel hook in the authentication route to send users to your JSP login page.
The user correctly authenticates against the JSP form.
In its response, your Java server sets some kind of encrypted, signed session cookie (this is how it generally works with Rails) as a credential. In addition, it sends a redirect back to your Ember app.
Ember boots again, ESA calls restore again.
restore pings your Java server again, gets a 200 back (thanks to the cookie), and thus resolves its Promise.
ESA learns that the user's authenticated, and redirects to the 'route after authentication'.
Keep in mind that, at its core, ESA can only indicate to the client whether the backend considers it 'authenticated' or not. ESA can never be used to deny access to a resource-- only to show something different on the client, based on the last thing it heard from the backend.
Let me know if any of that was helpful.

Authentication with Flask/Django and a javascript front end

I'm struggling to understand how flask_login or django knows when a user logs in that they retain access?
If I were to use ReactJs or Angular with flask-restful or django/tastypie, what is being added to the header/body of future json requests to ensure that my user stays logged in?
This is done via sessions, which is based on cookies. From the Flask documentation:
In addition to the request object there is also a second object called session which allows you to store information specific to a user from one request to the next. This is implemented on top of cookies for you and signs the cookies cryptographically.
and the Django docs:
Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID – not the data itself (unless you’re using the cookie based backend).
So, the requests to the server automatically include a cookie that indicates some ID that the server then uses to figure out what the session data should be for the given user. In general, when Ajax requests are made from client-side applications to the server, this cookie is included and so ensures that the user is considered to be logged in for those requests.
In some cases, you can also (optionally) manually add a special header to HTTP requests to indicate which user is logged in.
See also Securing RESTapi in flask for some more information.
If you use REST service then you should take a look at oAuth. In other words it uses token which you attach to every request from client to server and the last can determine which user sent this request by this token.
On the other hand, you can use cookie or session to determine a user status. And in this case you don't need to add any headers to your request.
Also I recommend you this package for Django - Django Rest Framework (there you can read more about token and auth via REST) and this extension for Flask.

EmberJS - Handling 3rd party redirect authentication

I'm using ember-simple-auth for my Ember app, but I don't have an API endpoint to authenticate users, rather it does a page redirect to the form and signs a user in, then redirects back to my app. (I don't own the authentication)
After authentication, it gets redirected back to me, so I know on the server side when a user has been successfully authenticated. How do I manually authenticate the users' session when they are redirected back to my app?
Currently I did a hack to write two cookies: ember_simple_auth:access_token and ember_simple_auth:authenticator.
I think setting up the session store manually is an ok solution in this scenario as that will trigger the session to be restored after the redirect (which is on startup of the Ember application). I'd maybe configure a custom authenticator that redirects to the external login page in the authenticate method. That way you have that redirect centralized and it will also be triggered automatically whenever Ember Simple Auth automatically enforces session authentication (e.g. from the AuthenticatedRouteMixin).