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

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.

Related

OAuth 2 token of MailChimp API call

I am developing an application from where I would like to create Campaign with list. The application flow is like this, User will click a Button then user will redirected to MailChimp login page, User will come back to my site after Logged in where URL is http://127.0.0.1:8000/home?code=f0f6949c8b5286c38a90aa4820776e14.This code is Authorization Code.
Now I would like to fetch Lists of that specific user who is logged in few moments ago. I can fetch my Lists using API key, but I need users Lists, I don't know users API key.
How can do that ?
I think I need OAuth 2 token of MailChimp API call to fetch User's Lists. How can I get OAuth 2 token of MailChimp API call ?
Thanks
From the MailChimp documentation (source: http://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-oauth2/)
How to Use OAuth2
For developers integrating platforms that require clients to access MailChimp’s servers, we recommend using OAuth2 for authorization. OAuth2 is a secure option that allows third-party applications to access a server without passing user credentials or API keys.
Before You Start
Here are some things to know before you begin the OAuth2 process.
Our server implements v10 of the OAuth2 specification, and supports Web Server Flow.
On the server side, OAuth2 is pure HTTPS, so we recommend using HTTPS for your redirect_uri.
We don’t expire tokens, so you won’t need to use refresh_token.
Register Your Application
When you’re ready to begin, register your application with MailChimp:
In your MailChimp account, navigate to the Account page.
In the account drop-down menu, click Extras, and choose API Keys.
Under the “Developing an App?” heading, click Register and Manage Your Apps.
Click Register an App.
In the fields provided, input your application’s information and click Create.
When creation is successful, you’ll see an Application created message appear, and more information at the end of your form, including the Client_ID and Client Secret. Do not share the Client_ID and Client Secret.
On this screen, you don’t need to save or change the information. Click Update or Cancel to go back to the Registered Apps page, or close the window.
Endpoints
OAuth2 exposes three specific endpoints, and one for metadata.
authorize_uri
https://login.mailchimp.com/oauth2/authorize
access_token_uri
https://login.mailchimp.com/oauth2/token
redirect_uri
Client-side, made available to the browser in use.
metadata
https://login.mailchimp.com/oauth2/metadata
Note
We support wildcards for the redirect_uri so you can provide
data-center-specific information for proper API calls. Wildcards work
as long as the redirect_uri appears to be a user-registerable domain
under a top level domain. For example, if you enter https://co.uk/ as
a redirect_uri, wildcard support won’t work. If you enter
https://mydomain.co.uk/, wildcard support will work. Domain detection
is based on these criteria.
A redirect_uri will also override the path portion of a URL, as well.
For example, a redirect_uri set to https://test.example.com/oauth.php
means that any URI starting with either test.example.com or
*.test.example.com will work (i.e.: https://test.example.com/somethingelse.php is valid).
Flow
To start your application’s connection to MailChimp, start by sending the user to the authorize_uri.
The user will input their username and password to approve your application. “Remember Me” cookies aren’t permitted here.
After the user authorizes your application, our server will redirect your user back to the redirect_uri, along with a code you can exchange for an access_token. The code is valid for 30 seconds.
Your application should then make an out-of-band request to the access_token_uri using the code our server provided.
Our server returns an access_token, which completes the official OAuth2 flow.
To complete the MailChimp flow, make another RESTful request using an OAuth2 client to the metadata_uri.
Our server will return a datacenter string, API endpoint, and login URL, as described in the following list.
dc:
The data center string, like us1, us2. If your API wrapper is data center aware, use access_token-dc as a standard API key.
api_endpoint:
Use https://{dc}.api.mailchimp.com. If you your API wrapper isn’t datacenter-aware, use this API endpoint and the access_token as your API key.
login_url:
https://login.mailchimp.com
Note
The access_token is used as an API key. Users don’t have access to these keys because they are tied directly to your
application. But, the user can de-authorize your application in
MailChimp, which removes and invalidates the token.
Configuration information
User-Specific configuration
client_id
635959587059
client_secret
0da3e7744949e1406b7b250051ee1a95
redirect_uri
http://192.168.1.8/oauth/complete.php
MailChimp standard OAuth2 configuration
authorize_uri
https://login.mailchimp.com/oauth2/authorize
access_token_uri
https://login.mailchimp.com/oauth2/token
base_uri
https://login.mailchimp.com/oauth2/
MailChimp custom configuration
metadata_uri
https://login.mailchimp.com/oauth2/metadata

Implementing OAuth 2.0 authentication with a Laravel API

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.

OAuth2 client without access token

So before I start, I'm a bit of an OAuth2 newbie, so still trying to really wrap my head around the various permission scopes and grants.
I've managed to successfully implement an OAuth2 server using the Laravel OAuth2 Server package.
The current site I'm working on will simply dogfood from the API, using the client_credentials grant type. I've managed to get this successfully working and can make API calls with the provided access token.
However, I'm wondering how I can implement an architecture similar to Instagram, Soundcloud, etc, who don't require an access_token for basic endpoints, just a client_id. How do they do this? Is this a custom grant type?
Preferably, I'd only like to start requiring an access token when accessing private resources, such as those for modifying user information, etc. As far as I'm aware, for these I'd need to use the password grant type, which isn't a problem.
OAuth has a few flows such as 2-legged or 3-legged which basically tells the developer how many requests he needs to make to the server to get the resource he wants.
For example, in a 2-legged flow you send a request with your id and secret (first request), you get back an access_token and using that token you can make other request for the resource you want (second request).
Comming back to your Instagram example, you can think at using just client_id as a 1-legged OAuth flow, because you make only one request to server to get the resource you want.
You can use such a flow for less sensitive resources, like a profile photo or user's nickname for example.
The implementation of a 1-legged flow is simple:
- If the user_id is valid and the application doesn't need user approval to access requested resource, go ahead and show the resource.
So implementing a 1-legged flow consists in checking if the client_id is valid and checking if the requested resource needs user permission. That being said, you can use 1-legged for requesting a user profile photo, but you can't use the same flow for requesting the user's private messages.
You can read more about each OAuth Flow in The OAuth Bible.
You have two different resources on your server - a) Resources that need some access checks b) Resources that are publicly accessible.
Actions on resources that need access checks should require that a user has been identified via the OAuth header in the request. In the context of Laravel - this would be a route with the 'before' key specified as Oauth.
Actions that do not need access could glean context about what user is relevant by building your routes to accept an argument that gives you context about the user. Let's say that you have a profile that a user can see without any sort of access. Your API endpoint for a JSON representation of that could be /api/profile/[user_id], where [user_id] is the ID of the user profile you would like to see. For these routes where you do not care about access, you can leave off the oauth before filter in your route declaration.

API Authentication & Authorisation OAuth 3-legged approach: Am I doing it right?

I'm working on an API and considering using OAuth (3-legged approach) for authentication and authorisation.
This is the basic idea:
In order for clients (mobile app or web app), to use this RESTful API the user will have to be logged in using identity providers/servers such as Google, Facebook e.t.c
Essentially 3 parties will be interacting here:
The mobile / web app: The one trying to access my API
The API: The site that contains data for the app to run
The identity server: The site that will allow the user to login in order to access the API
Now, the way that I understand this process (assuming I do). This would be the flow (summarised):
The user will try to access data from the API (consumer);
The consumer finds that the user is not logged in;
The user gets a page (with service provider buttons such as Login with Google);
The user clicks the button, and the service provider returns a login form;
The user logs in;
The service provider returns a page asking for specific permissions;
The user grants permission;
The service provider returns an access token to the user;
The user uses the access token to try the request again to the consumer (API);
The consumer takes the token and verifies it against the service provider;
The consumer grants access to the user.
First
Is this process correct (on a higher level), or have I completely misunderstood the whole thing. If it is not correct: Could you offer some tweaks?
Second
After this whole process. How does the consumer communicate with the user? Will I have to be passing around a token on every request made (between the mobile app and the API)? Or can I just use the user details from the service provider to identify the user?
Third
How exactly does the consumer (API) verifies the token provided by the user against the server? Is this already implemented in OAuth, or will I have to do it myself?
Forth and last
In terms of implementation, what would be the difference between the client (mobile app / web app) and the consumer (API)?
I'm new to this, and I am trying to implement it in PHP (the API). If you have any references to PHP code (sample implementations) or external resources, I'd really appreciate it :-)
I am also new for oauth but I'll try to help.
First you could look here for appropriate libraries which could help.
As for me your oauth flow is correct. A good explanations you can also find here.
Keep in mind that authorization server should return an authorization code which you use for obtaining access token.
So your questions:
1) Follow the second link and there - "Authorization Code".
2) With every request to you API you should send your access token. Something like
http://<your api>?access_token=7f813af1-381d-4dd7-b70b-b6a8399b2c00
3) Just use the libraries from the first link. I hope that they have already implemented this. :)
4)Can't exactly understand what you mean. Your client must be able to obtain access token, store it and send it with requests. Your API server must be able to receive access token from client, and give access to api if the access token is correct.

Securing a REST API and Slim Framework

I am fairly new to REST APIs, and I realize there are quite a few questions already posted. However, perusing these has actually left me more confused on how to handle this.
I have created a REST API using Slim Framework which I am simply using to transfer data. I won't be using user logins or authentication, so I believe to secure this I just need a system that using a public key and a private key, but I am just not sure.
If anyone has insight on the correct / most secure way to do this, or any tutorials / resources that would be great. Any help is appreciated.
You can use SSL to encrypt data in transit.
But SSL is just encryption; server-side ssl does not do authentication of the client, nor authorization. You can think of authorization as answering the question is the caller allowed to do what he is asking?. Authentication establishing the identity of the caller or Authentication is usually a necessary first step for doing authorization. Sometimes you don't need "the whole identity" - you just need to ascertain a particular aspect. For example, an automated washroom gate would not need to know who you were, but only if you were male or female in order to ascertain identity. In the same way, some services don't care who you are; they will allow access if you are calling from a particular network (ip whitelist) or if you carry a special token.
To allow the server to distinguish between authorized and unauthorized calls you have some options:
IP whitelist. If you know the IP address of the app or agent which will call your service, you can specify that in your service implementation. The service can check the IP of incoming requests and reject those that are not on the whitelist. This is sort of "implicit" authorization based on the caller's address.
a secret token, that the app provides in each call. You said you didn't want to do authentication, but this is a form of authentication. You might call it a "bearer token". Anyone who bears this token gets authorization. In your server you'd check the value of the token and reject any calls that don't match the well-known value. This works much like the IP whitelist except the token is explicitly passed, and does not have any relation to the network address.
a token + key pair. This is like a username / password, but it can be used to authenticate the app. Use this to provide the identity of the app itself. Check on the service side as above.
a username / password. To authenticate the user of the app.
You may want to combine these to produce the solution you want. In other words, the client request needs to be from the right I address, and needs to have a token/key for the app, and a username/password for the user, in order to be considered "authorized".

Categories