Token based simple authentication in Laravel (No passport) - laravel

I am new to laravel and creating a REST API. The client of the API will be mobile app only. There is no front end view to be shown in browser. I have created the routes and the controllers to handle API requests. Furthermore I deleted the Users table (created by laravel) because I do not need an Web interface etc.
I just want simple token based authentication at this stage ( I am aware there is passport authentication) but I can not even understand that at this stage.
There is only one table in the project.
Candidates
(id (PK), name, phone, details)
mobile app users are candidates also, should I create a token column in this table ? and manually create token at the time of register API and return it back as response ?
Please any simple guide or directions will help, I have search quite a bit online and there seems to be quite a lot many topics that show up such as guards, providers, passport which I am struggling to get.
Thanks,
Elliot.

First of all, you didn’t need to delete the users table. You can use it for api auth too. You just need to create a seperate token table.
However, if you want to implementit manually you need to do a lot of things manually.
This is a huge thing to impelement manually and it's not possible to describe it in a single answer. I will try my best to explain it as simply as I can.
You have to create a authentication system yourself that is for login. Define a middleware to check the authorization of the token sent from client to check the validity of every request (this is the guard part).
Also keep track of the token expiry time. Refreshing the token after each expiry needs to be done too (this is the provider part).
Now there are a lot things inside. Like keeping track of the device the request is coming from, providing different tokens for differenet devices for a single user etc.
If you are into learning how everything works then you can try to build one yourself. But if you plan on deploying it to a professional website, I would suggest try to get accustomed with passport. Reinventing the wheel is really not necessary. I hope it gives you a basic idea. If you have any more questions feel free to comment.

Related

Laravel Vue SPA - Social Authentication

Back Story:
I recently got into Web Development, and I would really appreciate it if you guys could share some great material/tutorials where I could learn, already got a couple of Udemy courses, and searched online but I still have some concerns.
For the first project, I would like to create an App which would be SPA. This would be a basic To-Do App, where users could log in and add To-Dos to their list.
Issue/Question:
How could I implement logging-in functionality only with Social Accounts (No regular Email/Password method)? If the user uses the login feature for the first time he is registered/added to the database where his data is stored, and for the second time, he would log in and fetch the data accordingly. I was thinking of Laravel Socialite, although, I'm not sure if it is used for SPA (Login without reloading/redirecting) pages? And if it is, do I need any additional forks/plugins?
I have found Universal Social Auth for that, however, I'm not sure if it does exactly what I need, and how to implement/configure it correctly.
All in all, I would really appreciate it if you guys could share some light here and perhaps share some tutorials or articles about that as well.
Backend:
Laravel
Frontend:
VueJS
VueX
VueRouter
Vue I18n
Axios, Vue-Axios
You need Laravel Socialite to get data about user from the identity provider (it could be Google, Github, Facebook or something else). It will use Oauth2 protocol.
You will store client_id and client_secret from the third party authentication you want to use. User will click for example Sign up with Google and it will redirect him to Google login page. If he fills correct username and password you will get his user information by using Socialite::driver('github')->user() .
You can use updateOrCreate() method to create user if it doesn't already exist in your database or just to update his data. Email or username fields could be identifiers or whatever is unique and works for your case.
After you found the user in database or created a new one, you should log in him to your application using session cookie or some kind of token.
Whole auth proccess is happening on the backend side, only when you successfully log in user to your app you can issue cookie to the frontend Vue side. So to answer your question, yes you can use Socialite with SPA.
Don't mix Laravel Socialite/Oauth2 with authentication proccess/Laravel Sanctum.
Former is for retrieving user data without registering on your site. Latter is for actually giving access to your API for specific user.

Secure public api for mobile app with laravel

I Guys, i have to create a mobile app that need to make a request to a laravel endpoint, app no require registration or login, which is the best way to protect my api? To make sure the only my application can call it?
Thanks!
There's no full proof method of securing your api, because with the right tools and following some tutorials on the web, anyone could view your whole api request, headers, tokens, etc.
Anything you do or store on the app is already compromised, so signatures,ssl, encryption,tokens, etc are not that helpful if malicious users have access to the app. It can make it more troublesome for malicious users, but a dedicated one could overcome it.
Using authentication atleast forces users to register before they can use your api and you can block the user when needed. Along with requiring email verification, users who wish to misuse your api would then need valid email addresses atleast. But since you mention securing without authentication, this goes out of scope.
You can secure your api somewhat by using rate limiting. laravel has an inbuilt rate limiting with the throttle middleware. You can use this to restrict the number of times an api can be called in a particular time interval by an ip address.
Next would be Ip blocking. If any malicious activity is found, you could block the ip address. But this can be overcome with a vpn, and a malicious user could also block someone elses ip in this manner.
Captcha can help against bots, but would also annoy regular users.
Another method would be restriction with cors, those who have faced cors issues know exactly how annoying it can be, but it wont work on native apps (or you could try pwa).
And in a worse case scenario you could go with some terms and conditions and some legal action
A simple solution You can create a table for devices with api key which will be generated for each device app, and always use it to send requests to the api end point, then used it to fetch data from the rest api. The same process like if you are loging in, but you will use the api key unstead and the key will be fixe not refreshed evrey time.

Does token auth make sessions unnecessary?

My question may be answered here, Are sessions needed for python-social-auth, but I feel as if I'd be making assumptions and would like to be positive regarding my understanding (NOTE: I'm not using django, I'm using mongo express react node, I'm guessing django might come with sessions built in or something). I followed this guide https://medium.com/hyphe/token-based-authentication-in-node-6e8731bfd7f2 to add token authentication and user login to my CRUD web app, works great, users are authenticated properly, routes are protected. However, everywhere I read about the fundamentals of session and session management states that "every web application in the world that maintains user data has to deal with sessions" (source: https://nodewebapps.com/2017/06/18/how-do-nodejs-sessions-work/). Currently, my react client uses setInterval to regularly check if the access token will expire soon enough to receive a new one via the refresh token. Is implementing sessions required for my app? If so, what is it that they add that I am missing?
It depends on the type of application.
If the resources being accessed using a token are not user specific, then sessions are not useful.
However, in a scenario where the resources are unique for different users (e.g. one has to sign in, etc), then it's wise to implement both sessions and access tokens.
Remember that tokens can also be saved within a session. Checkout 'express-session' to implement sessions in expressjs.

Using o-auth to authentify users on my API

I've got a project made of two websites:
The front : A Laravel website without database and logic (just showing static pages and my javascript)
The API : A project using Lumen/Dingo API with my endpoints, my database, my logic and my models
I want to allow my front to ask data to my API depending the user.
Ex. I want to log the user, retrieve his friends, add some post to his
account, etc. (from the Javascript)
What is the best solution?
Using an identification per user (using o-auth or JWT)
Allow my front project to ask to my API then each javascript call needs to use my front without knowing my API) (In this solution I need to create routes similars to my API's routes)
Identification per user is always a better solution as the claims can be decided per user, also in future when it is required to provide permissions to access API based on claims or roles, it becomes easy to give information using the claims and amount of access you can give to a specific user.
So the way it will work is:
There will be identity server which will be containing the list of users in the system, and also the clams and scopes per user.
The API project will trust the identity server, that means any token provided by the identity server can get verified.
Based on the token per user your API app can decide how much information you want to give to the user.
That way in future you can have methods based on roles, claims and users will be provided with only the information that they have access to.

Best practice in securing user creation for a REST API

I'm currently working on a iphone/android project where the mobile talk ta java backend server through REST API calls.
The Java backend is done using Spring and its Authentication system (with a JSESSION ID token)
I'm not an expert in security but I can see that if not implemented correctly there could be quite a lot of issues.
One of my biggest concern would be user creation for example.
When the app creates a user it simply makes a POST request to (url.com/rest/create)
How can I avoid, server side, that a malicious user puts this url in a loop and create thousands of users ?
What are common best practices to secure API calls ?
Is the Spring Authentication token enough ?
Thank you!
It's not really possible to prevent a client from making many calls to your server. A malicious user can create a script or application firing requests to your server.
The solution is to authenticate and authorize the calls to the server. You give certain users (for example administrators) the privilege to create users. You trust those users to behave in a correct manner. You have your users authenticate before they call the APIs on your server. Then, on the server side your check who the user is and what he/she is allowed to do.
If you are still concerned about privileged users not behaving, you can assign quota to each user on the actions they are allowed to perform.
The hightech solution (with as much framework fuctions as possible) would be
first: have a created-by and created-date field at the entity you want to protect (I recommend to use Spring-Data-JPA Auditing for that).
second: create a custom spring method (or web) expression method that is able to check how many items the current user has created in the (for example) last 10minutes and if this are more then (for examle) 20, then return false (or make them parameters of the method).
Then you can protect your method (or url) with that expression (#PreAuthorize("createsNotExeced(10, 20)"))
But this is the high tech solution - it would be quite intresstion implementing them when one wants to learn spring security. (and you would need to add some caching, but this is also a Spring feature).
The lowtech solution would be: put an list of timestamp in the users session, and add an new item to that array whenever the user creates an new item. When the last (for example) 20 timestamp enties are within the last (for example) 10 minutes, then throw an TooMuchHeavyUseRuntimeException or somthing else.

Resources