AngularJS + Laravel 5 Authentication - php

While building my SPA with angularJS, i came to the point where i want to implement user authentication in my angularJS website. However, i have no idea where to start and what the best practices are.
Basically i have a sure that can have one or more roles. I've looked for examples so i could get a basic understanding of how to handle this properly, but so far i've only came across examples that are very simple or are not so secure (like this).
So my question is, how to I implement a authentication service using REST (or custom API urls) to authenticate a user, and then display the user information on the page using angularJS, while also ensuring best security coverage by using (for example) the csrf token from Laravel?
Thanks in advance,
Nick van der Meij

I'm making an AngularJS app and an API RESTful made with Laravel 5 for the backend, and my approach for the authentication was:
Installed jwt-auth. Basically extends the Auth model of Laravel adding authorization with tokens.
Added simple role package to laravel. I used permiso. Has multiple roles/user and permissions/role. Very simple.
Added jStorage to frontend. (you can use AngularJS module instead).
So the steps are:
Frontend send user credentials (email and pass).
Server checks, jwt-auth makes a token to that user and send it backs.
Frontend save the token on the browser storage (no csrf needed with this approach).
All next calls to the API are made with Authorization: Bearer header (or with ?token=... )

I like the same approach that #neoroger takes using JSON Web Tokens with jwt-auth. I used the Satellizer package for storing the token on the front end and to send it along with each request to the API afterwards.
I put together a couple tutorials that show how to implement the two packages if you are interested:
https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps
http://ryanchenkie.com/token-based-authentication-for-angularjs-and-laravel-apps/

Related

Laravel Authentication API Sanctum – With Custom Database

First important information: I’m new to Laravel, so your patience is appreciated.
I’m currently migrating a framework of mine to Laravel and still in the early stages. I know that Laravel has it’s own database construction mechanism that is recommended to use the migrations and the Models, however, for my purpose, I’d like to use my own database that I use in other systems that I’ve built in the past. The idea for this system is to have a shared database, but operable through different tech stacks.
This is my current scenario:
Laravel 8
Sanctum 2.14
Frontend (Laravel):
I’ve built a very simple login page that has a controller and sends data (user and password) to my backend (Laravel). In the backend (different server), I grab the data and check if the data is correct. Being correct, I send a json response with some data, like:
returnStatus = true
loginVerification = true
IDCrypt = asdfasd4fa654sd54a (encrypted ID to grab in the frontend again)
Up till here, it’s working fine, as I wanted and very similar to my legacy systems.
My idea would be to get this response in the frontend, via auth token managed by Sanctum and use a middleware to check the token in order to let the user access some web routes.
I’ve watched some videos, but I’m only finding videos that use all the database mechanism that Laravel provides.
However, my intention would be to generate the token with data from my own table and data objects I created (without any existing Laravel´s models).
Is there a way for me to do this?
How would I set the token in the backend and include in my response?
How would I grab the token in the frontend in a secure way?
Lets say you have a model LegacyUser and this is your existing authenticable entity.
In this model simply override methods defined in the Laravel\Sanctum\HasApiTokens trait. Specifically createToken and the tokens relation for your use case by the sounds.
Then you can create tokens anywhere like usual with
$user = LegacyUser::find( $id );
$token = $user->createToken('token-name');
Then us the token as usual.
NOTE: if you're also changing how the tokens are stored/retrieved you'll need to set the token model, docs cover that here: https://laravel.com/docs/8.x/sanctum#overriding-default-models
If you want to avoid using authenticable entites (ie, no laravel models) entirely that's going to be more complicated and Passport might be a better shout, as client_credentials dont need to be associated to a user entity.
Alternatively: Write your own middleware that is compatbile with your existing auth process.

Could I benefit from jwt in my Vue app when using Vuex?

I am building a Vue app that uses pure PHP (no PHP framework) for its back-end. For my authentication system, I thought that using jwt(JSON Web Tokens) could help me. So I searched the web and found this article and also this one to help me build a login-register system with the help of jwt. I have no problem in implementing these articles in my front-part (Vue) and back-part (PHP) of my app. Currently I can send a request when the user register to the site and send back a jwt to the front-part with the help of firebase php-jwt library.
But the main question comes here. As I know from Vue ecosystem one of the reasons that we use Vuex is to store some data (state) globally in our apps and without calling a server we could use them anywhere (or in any route) in our Vue apps.
By reading one of that two articles, I noticed that finally the jwt is stored in Vuex and when the user wants to see an authorized page (a page that needs Authorization) the Vue app checks the Vuex to see if the token exists or not and if it exists, the app allows the user to see that page.
By reading the second one I noticed that jwt is useful when the user sends request to the back-part of site. In that case jwt is decoded and if it is valid (for example the expiration date is OK or ...), the user can access to an authorized page.
With the description above what is the benefit of using jwt in my Vue app? If I store just the id and user-name of user, it could do the same task for me. In other words, If I want to ask my question clearly, the problem is when I want to use Vuex and not send request every time to the server, I don't need and can't benefit from jwt (am I right?). Similarly when I want to use jwt, I could not benefit from Vuex. Because I must send request each time to find that the jwt is valid or not and after that decide about the user.
If I understood correctly and there is a contradiction for using both jwt and Vuex, why there are so many tutorials that speak about authentication a Vue app with jwt? Also if my understanding about jwt is correct, does that mean that when the jwt is expired I must ask the user to login again and again (regardless of using or not using Vuex)?
Could anyone please help me to have a better understanding about this problem to have better decision about my authentication system?
With the description above what is the benefit of using jwt in my Vue app?
JWT is used in authentication. You could use cookie sessions if you want.
I don't think it has an impact on your app. Probably save you some few round trips if your JWT happens to contain some data you need like user id.
the problem is when I want to use Vuex and not send request every time to the server.
I am not sure how these two are related.
If you need to make a request, then why would you use Vuex?
Vuex is a state management library.
If you need to do a request, then do a request.
Vuex does not relate to JWT in any way.
If you decided to put your JWT token in Vuex then that's your decision. Some put it in browser's localStorage or cookies.
Similarly when I want to use jwt, I could not benefit from Vuex. Because I must send request each time to find that the jwt is valid or not and after that decide about the user.
There's a lot of things you can store in Vuex that you don't need to do a request first:
Global component states e.g Login/Signup modals, NavMenu, Audio/Video player
Category filters like you see in Amazon or any shop-related apps
I am not sure what you are doing that you need to send request each time to find out if jwt is valid or not.
If something needs to be done on server-side then it has to be done on server-side whether you use jwt or cookies.
Also if my understanding about jwt is correct, does that mean that when the jwt is expired I must ask the user to login again and again (regardless of using or not using Vuex)?
JWT is a format. If you use OAuth2 for example, there's "access token" and "refresh token". You can get another "access token" automatically with "refresh token" and so that might mean you don't need to show login form again.
You could also just refresh your JWT token each time if you want. I'm not sure about the implications of that but there's a lot you can do.
These links might help you:
https://stackoverflow.com/a/36932032/10975709
https://stackoverflow.com/a/45214431/10975709
My question for you is:
If you were not to use JWT and instead just use cookies, how would things differ? (Aside from the technical aspects like needing to refresh tokens)
You are probably approaching/thinking/using JWT the wrong way.

How should I create my API for mobile applications (Needs Authentication)

Background
So I've been researching quite a bit for the past week about API's and have been reading about concepts and also programming one.
Currently I have a website which is programmed in PHP using a popular framework called Laravel. The website has a user database and users are able to log into the dashboard on my website, everything works as I want it to for my website side.
Now for the next project of my business i'm focusing on creating my mobile applications (IOS & Andriod).What I need for these mobile applications is being able to login through the application UI (not being redirected to my site with a callback URL) so they are able to view and manage the dashboard.
The method of authentication and authorization that i want to use for my application will go something like
Client asks user to login through UI
User enters credentials
Client sends a request to login to the API
The API checks if the credentials are correct
API creates a token which is stored in token database linked to user ID
API returns 200 OK with a json response or something like this
{ "token" : "OLS25usJIay81hdy81", "expiry" : 3/06/2016 14:00}
Client remembers token and expiry
Whenever a user/client makes a request such as api/v1/mystuff/orders it sends the token with the request(probably through the http headers?)
API verifies token, gets user ID and finds users orders
Questions
I know this is one hell a question and i'm not asking you people to program my entire software haha but what I need to know is
What should I use to create the API (needs to be PHP, and preferably laravel integrated)
What are some good resources to help me program my API
Is there any suggestions/changes you'd recommend?
Requirements
Username/Password authentication
Token Authorization
Login through app UI (Not on my website with a callback)
Notes
My website has a SSL cert.
Laravel is definitely a very good choice to create your API and your plan for authentication and authorization is pretty solid.
I could recommend for you to use the JSON token authentication package for Laravel https://github.com/tymondesigns/jwt-auth
You can see some tutorials here:
https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps
https://www.sitepoint.com/how-to-build-an-api-only-jwt-powered-laravel-app/
I would also recommend this API package https://github.com/dingo/api which will save you a lot of work.
If you need some help you could watch this series https://laracasts.com/series/incremental-api-development from Laracast, which requires a subscription, but it's more than worth it.

REST API backend for mobile application (android/iOS)

I am developing a backend for mobile app. I have developed a user authentication module where, the app will be sending the username and password as basic auth and if the user is authenticated I will sent back a jwt token which can be used in the rest of the requests.
On the client side, once after a user is logged in, the app shows him a feeds screen which contains some data.
Now do I need to seperate these two APIs? Like once a user is logged in successfully, he will be sent back the jwt token and well some user details. Should I sent the data which is required for the dashboard screen as well as a response for login? In that the case the app will get datas in a single api request (login) and doest have to make another call to my API.
Is this a right approach?
Ideally it should be kept seperately but I think that depends. If making that single request is (and will ever be) the only thing the application does, I see no reason for making 2 requests. You can simplify things by making just 1 request.
But, if your application is going to be extended or if its already got other features i think it is best to keep them seperate. Since then you'll have more flexibility with your application.
Yes ,You should separate those two authentication and dashboard REST API as-
It could be possible that there should be more client app using your Rest API in future and they may not require dashboard data.However you can have mechanism to share user detail in authentication API itself as you are anyway authenticating user .However share access token in authentication api along with it's expiration timestamp .Some of Client app which are using your REST API might have use case of autologout from app based on accesstoken get expire.In such case expiration time would help.

How to authenticate Zend Framework 1 users to access Laravel 5 API?

need your ideas.
I have a ZF1/Postgres application. It has its own users and all that.
Now I would like the whole application to be API-driven. I started to build
RESTful resources in a new Laravel 5 application. The Laravel app will talk to the same Postgres DB. Eventually, I want to get rid of all the DB calls within the ZF1 app, so that Laravel app is in charge of that.
The question is: I would like to add authorization for each API call, so that I know which users produce those calls and could act accordingly. What is the best way to authenticate users, so they could access Laravel endpoints?
If you want to use RFC-standard oAuth2 authentication, I would go with https://github.com/lucadegasperi/oauth2-server-laravel
Assuming you do, you'd probably want to use the "password" grant-type for internal authentication. Your client would hit the /oauth/access_token endpoint for a token using the user's username and password, which would return an access token good for the rest of the API.
To protect a route, you'd put it in the Route::group(['before' => 'oauth']...) section. To access an oauth-protected endpoint, you'd put the token in the HTTP header "authorization": "bearer ".
If you aren't using the standard laravel Users model, you may have to do a little tweaking. Most of it is covered in the oauth plugin wiki.
If the API is not public and there isn't any change to access it directly from the internet I wouldn't use any authentication. I would pass the userId in a custom http-header and and authenticate via Auth::loginUsingId(1) this will be cheaper then doing real authentication stuff. Therefore you have to map App\User to your existing user-table.
If you want to do real authentication take a look at RESTful Authentication
For inspiration on how to use Laravel for a REST-Service take a look at the dingo/api package (currently only Laravel 4, 5 is in progress).

Categories