How to track a user is logged in or not using api? - api

I am creating api using cakePHP. I have created an api for user log in. This log in functionality is working fine.
Here is the log in function -
public function login(){
if ($this->request->is('post')) {
$user = $this->Auth->identify();
}
}
Now, the I am facing problem is, how I can test from other api that is the user is logged in or not? In web application it can be done by default auth system ($this->Auth->user()). But I am not getting how I can check is this user logged in or not from another api. Do I need to send api parameter to each api request ? or any other suggestion ?
Note : I can't send any token in header. Because in header I am sending jwt token. Because in my application there are two kind of authentication. One is log in or not? and another one is depending some other input from user. That is handling by jwt. So jwt token I am already sending by header. So header is already used.

A couple of things to clarify.
In a regular app, the user logs in with a post request and on successful authentication a session is created. This session is a bit of information that the user supplies in each of the following requests and the server then recognises the user. This accomplished by the Auth component in it's default settings.
In an API you could do the same: the user logs in, receives the session and attaches the session cookie-like object on each following requests. (Example of such a Python client.) However, this is not considered good practice as APIs should be stateless (so without requiring something like cookies). The solution of working with tokens, for instance hashes of some secret token together with a timestamp. The Auth component also supports this pretty well. After setting it up, you can simply call $this->Auth->user(), like you would normally and it returns either false or an array of user information. See link below.
Note that by default this authentication type will block unauthenticated users, so you will never see ->user() return false unless you make pages as public.
See also:
(Cookbook > Authentication > Creating stateless authentication systems)

Related

Leveraging REST API's stateful token-based authentication pattern in its sole client (a web application), restricting some pages to loggedin users

I'm working on a REST API and a web application that will work off said REST API. The REST API implements a stateful token-based authentication pattern. Ultimately, allowing users to exchange their user credentials for a time-limited authentication token that identifies who they are.
So for example, a request such as:
POST: http://localhost:4000/api/v1/tokens/authentication
REQUEST BODY: {"email": "my_email_address", password": "my_password"}
would yield a response like:
"authentication_token": {
"token": "GAHZQS3IEIE6ELF7IHC6GK7M5Y",
"expiry": "2022-07-19T02:49:09.4194657+01:00"
}
If the user credentials that the user entered were incorrect, the user would not receive the authentication token.
The user needs to include the token in any further requests so that the REST API can identify the user. Some API endpoints are restricted to just logged-in users/users with certain permissions. And the token allows the REST API to know what sort of user it's dealing with. The token corresponds to a user id.
There will be a separate server from the REST API server serving the web application pages. But the pages will be populated with data from the REST API via the javascript fetch API.
I am happy with the REST API authentication. But I also need to restrict access to the web application pages based on if the user has logged in or not.
I want to leverage the existing REST API authentication but have never done something like this before so would very much appreciate any input you have.
Currently, I'm thinking of doing something like what's listed below. Do ye see any problems with it?
User accesses login page, enters credentials, and clicks 'login' button.
On clicking the 'login' button a request to the REST API is made:
POST: http://localhost:4000/api/v1/tokens/authentication
REQUEST BODY: {"email": "my_email_address", password": "my_password"}
If the credentials are correct, a token is returned, such as:
"authentication_token": {
"token": "GAHZQS3IEIE6ELF7IHC6GK7M5Y",
"expiry": "2022-07-19T02:49:09.4194657+01:00"
}
This token is added to a cookie for later use. i.e for when making another request to the REST API via the fetch API.
I'm thinking of adding another REST API endpoint that will simply validate a token i.e state whether or not the passed token is still valid and that the user is still logged in.
The webpage server can then call this endpoint to ensure the token is valid before showing a user a page that is restricted to just logged-in users.
Or maybe, instead of a validate token API endpoint, I should have a 'get user by token' endpoint. That will return user data if the token is valid. That way the webpage server could also get to know the type of user account that is associated with that user and could then also restrict pages based on the user type. It might also come in use for populating pages since nearly all pages will contain some user info e.g a profile image.

Authorization between nuxtjs and the backend API

I have a Vuejs application created using Nuxtjs. I am also using Django as the backend server, and I made an API to interact with the backend server (Django) and front-end app (Vuejs/Nuxtjs). And any API related fetch are done in the AsyncData function of the page to render the data on the server-side using axios. Also, I am using json web token authentication, and the API generates a jwt token after successful login which is stored in the cookie. So on the backend, it will always check for the request's authorization header for the token. If the request is from a logged in user (authorized token) then return authenticated json data, or else return non authenticated data.
The problem:
When the user navigates to the app, I would like to check if the user is authenticated. If the user is authenticated, render the authenticated page. If not then display non authenticated page.
My thoughts:
When the fetch is done from the App on the AsyncData function, I would check whether there is any value for the cookie. If there is then send the token with the request's authorization header. But, since the page will be rendered on the server first, and not on the client side (where the cookie actually is) it will never find the token for the authorization.
How can I check if the user is already logged in or not so that I can get authenticated and non authenticated data respectively from the API?
Update
When I successfully log in (post authorized email and password), I get a json response back with the token, which I set in the cookie like this:
this.$cookie.set('my_auth_token', this.token, {expires: 15})
How can I retrieve client side cookie and into the nuxt server for server side rendering?
Cookies are exposed in the (Express) Nuxt server through middleware.
Specifically, they can be read from the req.headers.cookie property. You can see an example implementation of this in the Nuxt documentation.
Regarding your implementation: fetching the privileged data from your API using Node would seem to be the ideal way to delegate session handling to that single service (rather than both) and provide SSR for your users.
If you've chosen to instead implement your session handling on the Django service then you'll need to "forward" your cookies by passing them into your axios request headers.
I did something similar using Firebase authentication. There is an example project on Github as well as a blog entry outlining the important files and configuration used in the application.

Symfony 3 authentication provider fallback

I have implemented authentication mechanism on some mobile application using JWTBundle with symfony 3. Until now the process requires users to submit both their email and password in order to authenticate. This works great.
Today I would like to grant access/create_account using Facebook authentication.
From the mobile app, users will access the application without submitting any password but instead FB will probably return user's Facebook identifier along with some other info. I will then post those datas to login_check route.
At this point I need a way to check (at the very beginning of request processing flow) whether login_check POST datas are standard username/pwd credentials (which I guess are handled through daoauthenticationprovider by default ? which in turn pass the processing to JWT in order to create a authentication token) and if not, fallback to another custom XXAuthenticationProvider to handle those datas (eg. if a facebook identifier is present then lookup the user account with FB API, do stuff … then create a JWT token).
I read couples of articles dealing with Symfony's Security components but none explained the whole thing clearly neither exposed a way to proceed. I still have difficulties to figure out how I could hook into the security firewall to achieve this.
Is this a way to go and how can I achieve this ?
Thank you.

User authentication and login flow with Ember and JSON web tokens

I'm trying to figure out how is best to do authentication and login flow with Ember. I'll also add that this is the first web app I've built so it's all a bit new to me.
I have an Express.js backend with protected endpoints using JWTs (I'm using Passport, express-jwt and jsonwebtoken for that) and that all works.
On the client-side, I'm using Ember
Simple Auth with the JWT authenticator. I have the login flow working (I'm using the login-controller-mixin) and correctly see the isAuthenticated flag in the inspector after a successful login.
The thing I'm struggling with is what to do after login: once a user logs in and gets the token, should I make a subsequent call to get the user details, e.g. GET /me, so that I can then have a representative user model client side? These details would then let me transition to the appropriate route.
See this example in the repo for an example of how to add a property to the session that provides access to the current user.

Laravel 4 [API] how do i check if i already logged in from the consumer?

I've been creating API and consumer by following Simple API Development with Laravel from Aaron Kuzemchak. I got the problem after I success to auth via API from my consumer; I do not know how to check it, if the consummer already success logged in or not at the other pages...
For example, at the first; I show the login page, click the submit button to check the credentials via API. The login attempt is working, success to logged in and redirect to dashboard. But, if I haven't logged in and accessed the dashboard from URL, i got the dashboard :O
The API server and the consumer have separated machine and the database only exists at the API server.
Am I doing this right (with the flow for the API and Consumer) ?
At the consumer, how can I get to know if the user already logged in or not (after success attempt the credential)? (somehow? someidea?)
Thank you before... :)
This question is very confusing, probably because I haven't watched that screencast yet, but shouldn't Auth::check() be what you are looking for? It will return true or false depending on if the user is logged in.
Just to make sure:
You have a back end API built from the tutorial posted here: http://kuzemchak.net/blog/entry/laracon-slides-and-video
You're using HTTP Basic authentication as described in the above tutorial
You're building a (consumer) front end web interface for users on a separate server
Your consumer interface uses forms based authentication (a login form)
The backend API uses HTTP basic authentication (and the consumer sends an API key for the user with each request). As such, the backend won't keep track of a user being logged in. That means your consumer interface will need to do this.
You could use the Laravel Auth class for this normally, but your front end would normally have access to the database and the bundled authentication drivers could just check a username/password.
I'd say your options are:
Store details of the user in a session using the Session class (feels a bit nasty but simple)
Write an authentication driver and then use the Auth class (advanced but cleaner: http://www.karlvalentin.de/1903/write-your-own-auth-driver-for-laravel-4.html)
Just talk straight to the database using the existing Auth class and Eloquent