Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Nayanabvreddy opened this issue May 30, 2019 · 1 comment

Comments

@Nayanabvreddy
Copy link

Nayanabvreddy commented May 30, 2019

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
Copy link
Owner

ncarlier commented Jun 2, 2019

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, ....).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants