ncarlier / kong-integration-samples

Samples Kong integration.
https://blog.worldline.tech/2018/05/16/api-gateway-oidc.html
122 stars 43 forks source link

how to access localhost:9000/chuck on the browser using the access_token generated from Keyclaok #9

Open Nayanabvreddy opened 5 years ago

Nayanabvreddy commented 5 years ago

Hello Ncarlier, The blog was very helpfull to work with kong. I need some help in how to access the protected api localhost:9000/chuck on the browser by passing the access_token. It would be really helpfull.

I have client side application running on localhost:3000 and this link takes me to sample realm login once i login and try to access localhost:9000/chuck it gives unauthorized message.

client side code:

function getchuck () { get('http://localhost:9000/chuck') }

function getfree () { get('http://localhost:9000/data1') }

const div = document.getElementById('response') function get (route) { let req = new XMLHttpRequest req.open('GET', route, true) req.setRequestHeader('Accept', 'application/json') req.setRequestHeader('Authorization', 'Bearer ' + keycloak.token) req.onreadystatechange = function () { if (req.readyState === 4) { if (req.status === 200) { div.innerText = req.responseText } else { div.innerText = 'Request returned: ' + req.status } } } req.send() }

server side code:

app.get('/free',cors(), function (req, res) { if (!req.headers['authorization']) return res.end() let encToken = req.headers['authorization'].replace(/Bearer\s/, '') let decToken = jwt.decode(encToken) let clientAccess = decToken.resource_access['demo-client'] if (clientAccess && clientAccess.roles.includes('subscribed')) res.json(['cat', 'dog', 'cow']) else res.json([]) })

I have added cors plugin to my services and routes. Screen Shot 2019-05-30 at 4 51 24 PM

Thanks, Nayana

ncarlier commented 5 years ago

Hello,

according to the network console, the API call seems to be made before obtaining the access token. Can you trace the API HTTP call to ensure that the request has an appropriate authorization header. If the header is ok, you should copy/paste the token part of the Authorization header to https://jwt.io/ to check that the token is ok. If the token is correct, the pb must be on the server side. Has the JWT library been initialized with the keycloak Realm public key to validate the token? You must trace the error to see the 401 reason (no token, invalid, obsolete, ....).