1.4.1 • Published 3 years ago

@tessaroto/security v1.4.1

Weekly downloads
18
License
ISC
Repository
github
Last release
3 years ago

Keycloak Security Module

Example

Installing module

$ npm install keycloak-security  --save    

index.js

const Auth = require('./lib/auth');

const config = {
	"basic": {
		"username": "services",
		"password": "MyPwd"
	},
	"bearer": {
		"keycloak_url": "http://localhost:8080",
		"realm": "MyDemo",
		"client_id": "my-react-client",
		"cache":{
			"cert": {
				"ttl": 10000,
				"stale_ttl": 100000,
				"stale_short_ttl": 1000
			}
		}
	}
}

const auth = new Auth(config);

async function test(){
	try{
		var authorization = await auth.validate("Bearer ${token}");
		console.log(authorization);
		console.log(authorization.hasRole("example-admin"))
		
		var authorization = await auth.validate("Basic ${credentials}");
		console.log(authorization);
	}
	catch(error){
		console.log(error)
	}
}

test()

Get user id

app.get('/brand/:id', protect("example-admin"),  function (req, res, next) {
  
  res.send({ userId: res.locals.user, authenticated: res.locals.authenticated});
});
ElementDescription
authorization.user.userIdIdentification user in keycloak (sub)
authorization.user.usernamethe username in keycloak (preferred_username)
authorization.isAuthenticatedif user is authenticated
authorization.roleslist of roles that user have.
authorization.hasRole(name)check if have the role name

Configuration

Example

const config = {
	"basic": {
		"username": "services",
		"password": "MyPwd"
	},
	"bearer": {
		"keycloak_url": "http://localhost:8080",
		"realm": "MyDemo",
		"client_id": "my-react-client",
		"cache":{
			"cert": {
				"ttl": 10000,
				"stale_ttl": 100000,
				"stale_short_ttl": 1000
			}
		}
	}
}

const protect = new Security(config);

Properties

ElementDescriptionDefault
basicFor use basic authentication, this is optional
basic.usernameUsername of basic auth
basic.passwordPassword of basic auth
bearerFor use bearer authentication, this is optional
bearer.keycloak_urlUrl of Keycloak
bearer.realmRealm of Keycloak
bearer.client_idClient Id of application that is configured in keycloak
bearer.cacheCache options, this is optional but if not defined will be using defaults values
bearer.cache.cert.ttlTTL of certification cache10 min
bearer.cache.cert.stale_ttlTTL of certification stale cache1 day
bearer.cache.cert.stale_short_ttl1 min