OpenApi Generator. Keycloak SDK done. Login Done!
This commit is contained in:
@@ -1,40 +1,37 @@
|
||||
import { HttpService } from '@nestjs/axios';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { KeycloakDataDto } from './dto/kc.data.dto';
|
||||
const querystring = require('querystring');
|
||||
import { Issuer } from 'openid-client';
|
||||
|
||||
@Injectable()
|
||||
export class LoginService {
|
||||
constructor(private readonly httpService: HttpService) {}
|
||||
|
||||
async login(loginDto: LoginDto) {
|
||||
const keycloakHeaders = {
|
||||
Accept: 'application/xhtml+xml',
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
};
|
||||
const { username, password } = loginDto;
|
||||
|
||||
const keycloakTokenData = {
|
||||
const keycloakIssuer = await Issuer.discover(
|
||||
`${process.env.KC_BASE_URL}/auth/realms/${process.env.KC_REALM}`,
|
||||
);
|
||||
|
||||
const openIdConnectClient = new keycloakIssuer.Client({
|
||||
client_id: process.env.KC_CLIENT_ID || 'client_id',
|
||||
client_secret: process.env.KC_CLIENT_SECRET || 'client_secret',
|
||||
grant_type: process.env.KC_GRANT_TYPE || 'grant_type',
|
||||
};
|
||||
|
||||
const kcData: KeycloakDataDto = { ...keycloakTokenData, ...loginDto };
|
||||
});
|
||||
|
||||
try {
|
||||
const res = await lastValueFrom(
|
||||
this.httpService.request({
|
||||
method: 'POST',
|
||||
data: querystring.stringify(kcData),
|
||||
headers: keycloakHeaders,
|
||||
url: process.env.KC_TOKEN_ENDPOINT,
|
||||
}),
|
||||
);
|
||||
return res.data;
|
||||
const token = await openIdConnectClient.grant({
|
||||
grant_type: process.env.KC_GRANT_TYPE || 'grant_type',
|
||||
username,
|
||||
password,
|
||||
});
|
||||
|
||||
return token;
|
||||
} catch (error) {
|
||||
return error;
|
||||
throw new HttpException(error.error_description, HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// {
|
||||
// "error": "invalid_grant",
|
||||
// "error_description": "Invalid user credentials",
|
||||
// "name": "OPError"
|
||||
// }
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { HttpService } from '@nestjs/axios';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { AxiosResponse } from 'axios';
|
||||
import { lastValueFrom, Observable, of } from 'rxjs';
|
||||
import { CreateUserDto } from './dto/create-user.dto';
|
||||
import { UpdateUserDto } from './dto/update-user.dto';
|
||||
|
||||
@@ -14,8 +12,6 @@ export class RegisterService {
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
// const obj = await lastValueFrom(this.httpService.get('https://jsonplaceholder.typicode.com/todos'))
|
||||
// return obj.data;
|
||||
return 'Find all Users';
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user