OAuth 2.0 Authentication

Add an OAuth 2.0 authentication layer with the Resource Owner Password Credentials Grant flow.

Create a Service

curl -i -X POST \
  --url http://localhost:8001/services/ \
  --data 'name=google-svc' \
  --data 'url=http://google.com'

We have service_id.

Create a Route

Replace service_id in /services/{service_id}/routes

curl -i -X POST \
  --url http://localhost:8001/services/google-svc/routes \
  --data 'hosts[]=localhost' \
  --data 'methods[]=GET&methods[]=POST'

We get route_id.

Test

curl -i -X GET \
  --url http://localhost:8000/

We will see Google website content

Create a Consumer

curl -X POST http://localhost:8001/consumers/ \
    --data "username=phong" \
    --data "custom_id=phong_id"

We get consumer_id.

Create an Application

Replace consumer_id in /consumers/{consumer_id}/oauth2.

curl -X POST http://localhost:8001/consumers/01b28940-7ece-4179-8b58-73b731d8e607/oauth2 \
    --data "name=oauth-2-app" \
    --data "client_id=cid" \
    --data "client_secret=cserect" \
    --data "redirect_uri=http://google.com"

We have client_id and client_secret.

Enabling the plugin on a Service

Replace service_id in /services/{service_id}/plugins.

curl -X POST http://localhost:8001/services/google-svc/plugins \
    --data "name=oauth2"  \
    --data "config.scopes=email,read" \
    --data "config.mandatory_scope=true" \
    --data "config.enable_password_grant=true"

We get provision_key.

Get token

Parameters:

  • authenticated_userid = custom_id
curl -k https://localhost:8443/google-svc/oauth2/token \
     --data "client_id=cid" \
     --data "client_secret=cserect" \
     --data "grant_type=password" \
     --data "scope=read" \
     --data "provision_key=kDNBwCVrTjQU5cLQI2FDyI6onAYpAIBI" \
     --data "authenticated_userid=phong_id"

We get access_token and refesh_token.

Test without oauth2

curl -i -X GET \
  --url http://localhost:8000/

Error

{
    "error_description": "The access token is missing",
    "error": "invalid_request"
}

Test with oauth2

Replace access_token in Authorization: Bearer {access_token}.

curl -i -X GET \
  --url http://localhost:8000/ \
  --header "Authorization: Bearer a503faf9-45b5-4fec-8334-337284a66ea4"

We will see Google website content again.

Refresh token

Replace refresh_token in --data "refresh_token={refresh_token}".

curl -k POST https://localhost:8443/google-svc/oauth2/token \
    --data "grant_type=refresh_token" \
    --data "client_id=ci" \
    --data "client_secret=csecret" \
    --data "refresh_token=a503faf9-45b5-4fec-8334-337284a66ea4"

We get new access_token and refesh_token.