Jirmed
Jirmed

Reputation: 441

Node.js API protected by Keycloak with Access-Type "bearer-only"

I am new to Keycloak. I have created the simples app in Node.js as per the documentation:

import express from "express";
import Keycloak from "keycloak-connect";

const keycloak = new Keycloak({});
const app = express();
app.use( keycloak.middleware());

app.get('/api', keycloak.protect(), function(req, res){
    res.send("This is API!");
 });
 
app.get('/', function(req, res){
    res.send("Server is up!");
 });
 
 app.listen(3000);

My keycloak.json looks like follwing

{
    "clientId": "mydemoapp-api",
    "bearerOnly": true,
    "serverUrl": "http://mykeycloakserver:8180/auth",
    "realm": "myrealm",
    "realmPublicKey":"MIIBIjANBgk... "
}

The Access Type of the client mydemoapp-api is set to "confidential". Using Postman or CURL i can generate the token and then access the endpoint /api with it. If I try to connect to /api without token I get access denied - so far so good.

I changed the Access Type to "bearer only" for mydemoapp-api in Keycloak admin. Then I created another client in the same realm mydemoapp-client with Access Type "public"

I have requested a token for client mydemoapp-client using Postman again. Then I used this token to access endpoint /api. But I always get Access denied.

From the documentation I understood that if no roles are specified and no other restriction are activated I should be able to log in to any client in the realm and then use the SSO token to authenticate to any other client in the same realm. But apparently I am missing some piece in the puzzle.

Upvotes: 0

Views: 3779

Answers (1)

Jirmed
Jirmed

Reputation: 441

I have found the following blog https://developers.redhat.com/blog/2020/01/29/api-login-and-jwt-token-generation-using-keycloak#test_your_new_client

It suggests setting Authentication Flow Overrides/Direct Grant Flow to direct grant for mydemoapp-client. And it works!

Upvotes: 1

Related Questions