This is an Nestjs implementation of the keycloak-middleware-ts package..
Installation
Install with yarn or npm:
yarn
ornpm
:
# yarn
yarn add nest-keycloak-middleware
# npm
npm i nest-keycloak-middleware --save
# pnpm
pnpm add nest-keycloak-middleware --save
Usage example:
// user.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { KeycloakModule } from 'nest-keycloak-middleware';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { User } from './entities/user.entity';
import { configService } from '../../infra/application/application.config';
@Module({
imports: [
TypeOrmModule.forFeature([User]),
KeycloakModule.register({
realm: configService.getValue('KEYCLOAK_REALM', true),
authServerUrl: configService.getValue('KEYCLOAK_URL', true),
clientId: configService.getValue('KEYCLOAK_CLIENT_ID', true),
clientSecret: configService.getValue(
'KEYCLOAK_CLIENT_SECRET',
true,
),
username: configService.getValue('KEYCLOAK_ADMIN', true),
password: configService.getValue('KEYCLOAK_ADMIN_PASSWORD', true),
}),
],
controllers: [UserController],
providers: [UserService],
})
export class UserModule {}
In your user.service.ts import the KeycloakService:
// user.service.ts
import { KeycloakService } from 'nest-keycloak-middleware';
In your constructor pass the KeycloakService instance
// user.service.ts
constructor(private readonly keycloakService: KeycloakService) {}
Create the interface, taking the necessary data
// create-user.dto.ts
export class CreateUserDto {
@ApiProperty({ required: true, default: chance.name() })
@IsString()
@IsNotEmpty()
firstName: string;
@ApiProperty({ required: true, default: chance.name() })
@IsString()
@IsNotEmpty()
lastName: string;
@ApiProperty({ required: true, default: chance.email() })
@IsEmail()
@IsNotEmpty()
email: string;
@ApiProperty({ required: true, default: '123456' })
@IsString()
@IsNotEmpty()
password: string;
}
As an example, use your keycloack context and create the user right away.
// user.service.ts
public async create(createUserDto: CreateUserDto) {
try {
const passwordHash = await bcrypt.hash(createUserDto.password, 8);
const user = this.userRepository.create({
...createUserDto,
password: passwordHash,
});
const ctx = this.keycloakService.createKeycloakCtx();
return ctx.users
.create({
...createUserDto,
username: user.id,
password: passwordHash,
enabled: true,
})
.then(() => this.userRepository.save(user))
.catch((error) => error);
} catch (error) {
throw error;
}
}
π€ Contributing
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
Show your support
Give a
Or buy me a coffee ππΎ
π License
Copyright Β© 2022 Hebert F Barros.
This project is MIT licensed.