File

src/provider/keycloak-apii/keycloak-api.service.ts

Index

Methods

Constructor

constructor(httpService: HttpService)
Parameters :
Name Type Optional
httpService HttpService No

Methods

Private Async get
get(uri: string, token: string, params?: P)
Type parameters :
  • P
Parameters :
Name Type Optional
uri string No
token string No
params P Yes
Returns : unknown
Async getCredentialsByRealm
getCredentialsByRealm(realm: string, token: string, params?: P)
Type parameters :
  • P
Parameters :
Name Type Optional
realm string No
token string No
params P Yes
Returns : unknown
Async loginWithUserMaster
loginWithUserMaster()
Returns : unknown
Private Async post
post(uri: string, data: D, config: C)
Type parameters :
  • D
  • C
Parameters :
Name Type Optional
uri string No
data D No
config C No
Returns : unknown
import { Injectable } from '@nestjs/common';
import * as qs from 'qs';
import { HttpService } from '@nestjs/axios';

@Injectable()
export class KeycloakApiService {
  constructor(private readonly httpService: HttpService) {}

  private async post<D, C>(uri: string, data: D, config: C) {
    const { METODO_ACESSO, IP_SERVIDOR } = process.env;

    const configAxios = config || {
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
      },
    };

    return this.httpService.axiosRef.post(
      `${METODO_ACESSO}${IP_SERVIDOR}${uri}`,
      data,
      configAxios,
    );
  }

  private async get<P>(uri: string, token: string, params?: P) {
    const { METODO_ACESSO, IP_SERVIDOR } = process.env;

    const configAxios = {
      params,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        Authorization: `Bearer ${token}`,
      },
    };

    return this.httpService.axiosRef.get(
      `${METODO_ACESSO}${IP_SERVIDOR}${uri}`,
      configAxios,
    );
  }

  async loginWithUserMaster() {
    const { KEYCLOAK_CLIENT_ID, KEYCLOAK_USER_ADMIN, KEYCLOAK_PASSWORD_ADMIN } =
      process.env;

    const config = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        Referrer: 'no-referrer',
        'Sec-Fetch-Mode': 'cors',
      },
    };

    const params = qs.stringify({
      grant_type: 'password',
      client_id: KEYCLOAK_CLIENT_ID,
      username: KEYCLOAK_USER_ADMIN,
      password: KEYCLOAK_PASSWORD_ADMIN,
    });

    return this.post(
      '/auth/realms/master/protocol/openid-connect/token',
      params,
      config,
    );
  }

  async getCredentialsByRealm<P>(realm: string, token: string, params?: P) {
    return this.get(`/auth/admin/realms/${realm}/clients`, token, { params });
  }
}

results matching ""

    No results matching ""