Implementing OAuth 2.0 authentication with a Laravel API - php

I'm currently building a web application which is an AngularJS frontend that communicates with a RESTful API built using Laravel. I'm making good progress, but finding it hard to get my head around how to handle user authentication.
I've been advised that I should be using OAuth for authentication, and I've decided to use it seen as it could be a learning experience for me as well. The package I'm using to handle this is oauth2-server-laravel.
The basic user story is that users can register their username/password combination for the application, and they then log into the application with that same username and password. They're only authenticated by their username and password, and not by any client secret. After login, they should be given an access token which will be send along with every future request to authenticate them on different API endpoints.
The OAuth2 library has a "password flow" grant type which seems to be what I need, however it also takes client_id and client_secret parameters, which I don't want. The request URI is something like this:
POST https://www.example.com/oauth/access_token?
grant_type=password&
client_id=the_client_id&
client_secret=the_client_secret&
username=the_username&
password=the_password&
scope=scope1,scope2&
state=123456789
But what I want is just:
POST https://www.example.com/oauth/access_token?
grant_type=password&
username=the_username&
password=the_password
How am I meant to provide a client ID and secret of a user that has yet to authenticate?
Is there a different grant I can be using, or is what I want to achieve just not suited for OAuth at all?

Take into account, that client id and client secret aren't parameters that you have to force your end-user to pass. They are static and defined in/for your client app (angular app in this case).
All you need to do is to create a record for your main app in oauth_clients table, and create a scope with full access in oauth_scopes table, and send this values when requesting token.
And that's all in fact.
Also, you may want to consider using implicit grant flow in case of building js-only application, because storing client secret and refresh token in a js app is insecure. Using implicit grant in a final product may look like login window on soundcloud and is more secure as the token is obtained server-side without exposing client secret.
Another way to go, if you still want to use password flow is creating a proxy for refreshing tokens. Proxy can hide your refresh token in encrypted http-only cookie, and your js-app don't ask your api for new token, but the proxy instead. Proxy reads refresh token from encrypted cookie, asks the api for new token and returns it. So the refresh token is never exposed. If you set token ttl for an hour let's say, then stealing a token would be quite "pointless*" in case of a normal application, and stealing refresh token would be "impossible*".
*Of course if someone really want he probably could hack it any way.
And yeah, i know this all looks a bit hacky - modal windows for logging in, proxy etc. But also searching on this topic i couldn't find any better and more elegant way of doing it. I think that's still a lack that all js-apps have to deal with if you want a token based authentication.

You are missing something with the OAuth specification. The client_id and client_secret are really important when asking for an access token when using the password method of OAuth v2. In fact, they are important for every method that gives you an access token. They identify the application or the server that has perform the request.
For example, let's say you have your API, 2 mobile applications and another server that do some tasks with your API. You will create 3 clients with their own client_id and client_secret. If your application has various access levels (they are called scopes in OAuth v2), the client_id corresponding to the other server will be able to call functions of your API that require the scope admin whereas your mobile application will only be able to call functions of your API that require the basic scope if you have defined scopes like this.
If your API grows up in the future, this is really essential. Another example, let's imagine you have given an API key (a pair client_id and client_secret) to one of your friend and he has build a nice mobile app with your API. If one day he starts doing naughty things with your API, you can't stop him very easily. Whereas you could have just removed his key pair if you had followed OAuth v2 principles.
OAuth v2 is not an easy thing to understand, take the time to read specifications and good tutorials before developing your API.
Some useful links :
The official RFC : https://www.rfc-editor.org/rfc/rfc6749
A tutorial on Tutsplus : http://code.tutsplus.com/articles/oauth-20-the-good-the-bad-the-ugly--net-33216

Just to add a bit to plunntic's excellent answer: remember "client" is not related to "user", so when I use a password flow I just define the client_id and client_secret as constants on the AngularJS app to tell the api backend: hey, this is the browser app that is being used to request a token.

Related

How to add an API with oauth2 on the top of Kong

I'm trying to add an API on the top kong with using oauth2 authorization plugin of Kong. The steps
I have followed as per their Kong documentation :
Create an API and add oauth2 plugin
Create consumer
Create an application
I got client_id, client_secret, provision_key etc from the above steps, but I'm wondering that if I need to create oauth2 server at my end or kong itself configured it at their end and we just need to call their endpoints.
I'm building my APIs in laravel.
I think we spoke really briefly on Gitter, and there I already said that it depends on your use case. I'll do a brief rundown of typical use cases, and where you need which kind of additional implementation.
Machine to Machine communication
If you need two systems to talk to each other from the backends, and these systems trust each other, you can use the OAuth2 "Client Credentials Flow". In this case, there is no "end user" identity involved, only the two systems which explicitly trust each other.
For this scenario, Kong is everything you need - you just ask Kong's API Token end point (<address of kong>:8443/your_api/oauth2/token for URI based routing, or fqdn.of.kong:8443/oauth2/token if you're using host based routing) for an access token using your client ID and Secret, and you will get one back.
Example:
curl --insecure -d 'grant_type=client_credentials&client_id=<...>&client_secret=<..>' https://<address of kong>:8443/your_api/oauth2_token
Your backend service will get some extra headers injected, such as X-Consumer-Id and X-Custom-ConsumerId which maps to the consumer you created in Kong.
Confidential Web Application with End User context
In case you need to use your API from a confidential (=classic) web application, and you need to have an end user context with each call, you might want to use the OAuth2 "Authorization Code Grant". In this case, you will also need an Authorization Server which you need to implement yourself.
The Task of the Authorization Server is to establish an end user identity (mind you: This is not specified in OAuth2 how this is done, and is up to you; you can federate to some other IdP, you can ask for username and password,...) and then to decide on which rights (="scopes") the user gets when accessing the API. This is completely up to you, and part of your business logic how to decide this.
The flow goes like this:
You (re-)direct a user to the web page of the authorization server
The AS authenticates the user (by whatever means) and decides on the scopes (by whatever other means)
The AS talks to Kong on two different levels
Via the Kong Admin API, to retrieve the provision_key of the desired API
Via the [/your_api]/oauth2/authorize end point, which it uses to get a redirect URI which includes an authorization code, in the context of the authenticated user and his scope (scope and authenticated_userid); to call this end point, you will need response_type=code, client_id, client_secret, provision_key, authenticated_userid (whatever is suitable) and optionally scope (scopes need to be defined on the API as well if you want to use this)
If successful, the AS redirects back to the web application, using the redirect URI returned by Kong
The web app calls Kong's [/your_api]/oauth2/token end point with its client_id, client_secret and code, using the grant_type=code
Now you will have an access token (and a refresh token) which lets your web application access the API on behalf of the authenticated user.
The Authorization Server has to be implemented by you; this is not super complicated, but you still need to make sure you know how to authenticate a user, and/or how you delegate this to some other IdP.
Public Client (Single Page Application) with End User Context
In case you need access to an API from a Single Page Application (like from an Angular app or similar), you should look at the OAuth2 "Implicit Flow", which is a simpler flow than the authorization code grant, but which has other drawbacks, like not being able to use refresh tokens.
This flow works in the following way:
Just like for the Authorization Code grant, you redirect the user to the Authorization Server
The AS establishes identity and decides on scope (once again, this is up to you)
The AS calls the authorize end point, just like with the Authorization Code grant, but this time with response_type=token
Kong, if successful, will return a redirect URI which already contains a token
The AS redirects back to the SPA, using the redirect URI from Kong, which has the access token in the "fragment" of the URI (e.g. https://your.app.com/#access_token=<...>&token_type=bearer&...)
Your SPA will now be able to use the access token to access the API, just like with the Authorization Code grant, on behalf of the authenticated user.
The drawback with this approach is that you can't (that) easily refresh the token, and that it's somewhat less secure than the Authorization Code grant. But dealing with SPAs, there are not many other secure ways of delegating access to it.
Mobile Applications
The last scenario I would like to touch here is Mobile Applications, like Android or iOS apps. For these, the last OAuth2 flow, the "Resource Owner Password Grant" can be used. In short, with this grant you exchange the actual user credentials (username and password) against an access token and a refresh token, so that you don't have to store username and password on the mobile device more than temporarily.
This flow also needs an Authorization Server to be able to use with Kong, albeit a less complicated one this time, even though you must implement an additional token end point (in addition to the one Kong has), which is not ideally described in the Kong documentation.
It'd go like this:
The mobile app uses its client_id (NOT the secret, the secret should not be deployed with the application), the username and password to call the Authorization Server's token end point
The Authorization Server checks username and password (by whatever means, you know the story) and decides on the scope (...)
The AS talks to Kong over admin API again, getting the client_secret for the provided client_id and the provision_key for the desired API
The AS issues a call to Kong's token end point [/your_api]/oauth2/token, like this:
curl --insecure -d 'grant_type=password&provision_key=<...>&client_id=<...>&client_secret=<...>&authenticated_userid=<...>&scope=' https://:8443/your_api/oauth2/token
Note that this call does not contain username and password; those don't belong here, you must check username and password against your own source of identity, Kong will not help you with that.
This call should return both an access token and a refresh token which you then store (as safely as possible) on your device. These replace the username and password, which must not be stored on the device. The access token can as with the other end user context flows (Authorization Code Grant, Implicit Grant) be used to access the API on behalf of the authenticated user.
Using Kong with OAuth2 is tricky and involved, but Kong can really help getting this right and separate your concerns.

Consuming private API REST (Android + Symfony)

I have a stateful php web application made in Symfony that uses cookies to keep alive the session of the logged user in the application(I have worked always like that, I'm really new in REST services).
I'm making a REST API using the business logic of this web application, so I can use it in different environments (Android at the moment).
In order to keep private the API, I follow the symfony cookbook(http://symfony.com/doc/current/cookbook/security/api_key_authentication.html), so the requests are served through a 'apikey' sent in header of every request.
At the moment, this 'apikey' is a dummy string hardcoded in my android code.
What I first thought to do with this 'apikey' is a login screen in Android that send to the API an user and password, those credential will be checked on the server side and if they are correct, send to the client a 'apikey'(based on those credentials) and then, somehow, store it in the client and then send it in header of every request of the API.
I'm misunderstanding something with this 'apikey' method? (probably yes, while I'm writting this it seems to me that this apikey is a more 'static' concept).
Isn't this idea a kind of 'stateful' that is against REST pattern? I mean, I keep stored something that is checked on every request.
What I want to achieve is to have a login in Android, check credentials in server side and then(if this check is ok) let the android app make calls to the API in a secure way...
How I should proceed then?
Thank you for your time!
I'm also learning such things with Android and Symfony. What i've come to understand is your API Key should be unique to every user, meaning that every user should have, as subscribed to your website, an API Key, which represents them. It will work like a unique login, except that using REST, you only need the API Key to be authentificated, instead of a login and a password.
In this case, your API Key should be hard to find. I guess you should use the user's ID and login, since they have to be both unique identifier, and make something out of it, like encrypting.
If you've learn more since, it'd be a pleasure to hear from you experience.
I've implemented the ApiKey "mode" in my Symfony web app.
From my perspective, after correct user connection (using login and password), you can generate a key resulting in the sha1 encryption of the concatation of any unique user info with the result of uniqid.

Secret token for communicating Ionic App and Laravel RESTful API

I am developing an Ionic App which consumes data from a Laravel 5 RESTful API. All the connections are protected (GET, POST, etc.) by username/pass and user roles, except the user creation.
My first doubt about security is to disallow connections from outside the App, avoiding thousand of user creations, overloading our server resources.
My idea is, when an user installs the app and opens it for the first time, to create a secret token which will be sent in every connection. Then check the device UUID and the secret token to ensure this is an authorized app.
What do you think of securing the connections this way? There is a better idea?
You need to look a JWT (Jot) JSON web tokens, they will solve the security issue. This can contain user id and other data like access level. Not things like security information or card information.
When a user authenticates Laravel sends them back a JWT which you store in local or session storage this replaces backend sessions.
It is generated by the backend using the parts that can be decrypted by the frontend and using a secret key to encryt the signature, if any of it is tampered with it will fail and deny access.
Every request angular will append the token to the header using a request interceptor and Laravel middleware will decrypt it and allow access to the route they need or return a error code '404' maybe.
If after install this authentication layer you can limit usage at user level on the backend.
But this should sort most of your issues, it a bit of a change in thinking but it does work and it solves a lot of sessions issues you get with ajax calls and it make load balancing easier because all server are looking for a token it can manage.
I was also encountering the same problems. But after search in google for a while I came to the conclusion that you can put up several walls against hacker, but for someone who is hell bend on hacking your app(ninja hacker) will find ways to use your app in malicious ways.
I also came across various ways you can protect your backend server(after google). These step generally make it difficult to use your app maliciously.
You can encrypt strings url using some algorithm and use encrypted string in program ie. https:\google.com\ is encrypted into something like \h09ae\hff00\hebab\h.... then in program String url ="\h09ae\hff00\hebab\h.." This way someone decompiling the app can't find your server backend url. In this case you need to decrypt the string url before you can use it.
Send sensitive data using HTTPS and inside the body of the request
You can verify if request is coming from the device by using google token. For this you will have to use Google API Console. Refer this link for proper android tutorial on this topic.
Lastly, sign key used when you create your apk is unique and ensure that your apk is not tampered with. So generate hash key of your sign key before it is upload to google play and save it in your server and programmatically get hash value of sign key and send it with very request to your backend.
Hope is helps you..

OAuth 2.0 (Tokens) for Login Functionality

I am here with some general discussion very famous and interesting topic "Token Based Authentication".
I need my registered users to login with API. Scenario is quite simple, We want to pass our login details to Server. Server will check the credentials with database. If credentials are proper then Server will create "Session Id" and return back to user (client end). In subsequent requests user just need to pass that "Session Id" to authenticate and access protected data.
Plenty of people suggest about OAuth 2.0 and also some people suggest about Custom Logic. In custom logic they asked to be very sure about security. I read documentation of OAuth and it's good and descriptive. I'm also liking it to use. But wherever I search for OAuth authentication, they are giving example of third party login.
I had installed Php OAuth extension at my side for supporting this feature. In examples they asked to create Request Token first using "getRequestToken" function. Using that Request token they asked to call "getAccessToken" function to get "Access Token". Using that Access Token just need to call "fetch" to get protected data.
Now my questions are,
In my scenario, Do i need Request Token? Is that possible to get Access Token directly
What is OAuth Consumer Key and OAuth Consumer Secret key? Do I need such keys in my application? I believe it's used to allow third party applications only. In my case I'm the resource owner and i'm the consumer.
Do you guys have any example for me to study?
Do you know any well known framework for OAuth for PHP?
Is that need any additional database support except "user" table? For storing OAuth details?
Any additional documents to study for this would be highly appreciated.
I read different Grant Types in OAuth but confused how to use to achieve my approach.
Thanks in advance.
From what I read, you do not need OAuth at all. OAuth is need if there is a third party involved that needs access to your user resources.
As you mentioned, you just need a Login API something like https://myserver.com/signin?user=john.doe#gmail.com&password=12345
After successful login, the server generates a GUID and stores it against the user. You can call it sessionId/cookieId anything you like. Response could be something like '{user:john.doe#gmail.com; sessionId=KJN93EJMQ3WEC9E8RCQJRE8F9E}'
For subsequent calls, the sessionId can be passed in the header.
Server validates the session and lets the user in.
Addtional considerations:
I am assuming your server is HTTPS and hence the user/pwd on the URL are encrypted.
For security you might want to invalidate the sessionId have the sessionId renewed periodically.
Have a logout on which you clear the sessionId against the User.
I think it standard stuff if not the logging in happening via REST.
The requirement that I posted before to login with OAuth2.0.
Usually people assume that OAuth2.0 is only for fetching data by Third Party application from resource center behalf of Resource Owner. That approach is called Authorization Code.
OAuth2.0 has various "Authorization Grant". There are four types,
Authrozation Code
Implicit
Resource Owner Credentials (User Credentials)
Client Credentials
After research, I realize that "Resource Owner Credentials" is best suitable for me. I found one perfect library that helps you to understand background process internally. Here's the GitHub link to download.
Found two major issues here,
When I use my Access Token created by my Mozila in Chrome. Surprisingly, It's allowing me to access my private data from other browser.
I'm unsure but will this approach work same with AJAX type of calls (jQuery tool)
If anyone has idea then please share.
Thanks,
Sanjay

Connect angularjs webapp to REST API (PHP)

I have a REST API written in PHP(Slim framework) and my API contains some admin routes for managing private data. I've implemented oAuth2.0 for authorization(this php implementation).
I like to use AngularJS for creating an admin webapplication so users can manage their own data.
I'm now using username-password flow but i'm reading that this is not secure because my webapp exposes client_id & client_secret.
I also looked into implicit grant ( designed for public clients) but it says that it should be for read only purposes.
I also want to use this API for supplying data for mobile apps. Users don't have to sign in for this but data isn't public.
Which oauth grant is suitable for this scenario / setup?
Take a look at Resource Owner Password Credentials Grant. Which is the 4th bullet point in the second link that you provided. password (user credentials)
https://www.rfc-editor.org/rfc/rfc6749#section-4.3
Simply put:
User sends their login and password
Server grants user access_token (equivalent to the old cookie session id)
User sends access_token with the remainder of their requests
Also,
If you want to give mobile devices access while keeping data private i'd suggest generating "free" accounts linked to mobile mac addresses. Then have them go through the above said authentication with their mac address as login / password as empty. That way you can implement the same user logic to mobile with throttle/ban/upgrade/etc per device.
I know I'm posting Python to a PHP question but it's not about the code. The example (http://python-eve.org/authentication.html#auth) explains in detail what auth methods are available for a good REST API and it might be useful for your application.
If you're not happy with implicit or username-password that leaves client credentials or authorization code.
Client credentials is not applicable in this situation because it's not possible to secure the credential in a javascript application running on a browser (it might not even be possible to use the client credential if you're talking about a certificate).
So Authorization Code is your only option.
However, you can't secure the client secret in the authorization code flow.
Implicit is really your only OAuth2 option for a browser application. There is a section in the OAuth threat model discussing the potential issues and mitigations. https://www.rfc-editor.org/rfc/rfc6819#section-4.4.2
Here is another question about the security implications of implicit grant. How secure is Oauth 2.0 Implicit Grant?
Since Stack overflow is dumb I can't comment since i don't frequent this site. However before I can offer a solution I am wondering what situation you have that required a user to not be logged in to update data?

Categories