Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use keycloak with NestJS properly

I need to use keycloak with NestJS and GrapphQL (type-graphql). There are some guides for using it with pure Express, but I'd prefer using with NestJS auth pattern. Can someboby give any suggestion?

like image 487
Yura Kovalenko Avatar asked Jun 27 '19 11:06

Yura Kovalenko


2 Answers

This is a kind of an old question, but since I just went through implementing it, I would like to point to a great tutorial Protecting your NestJS API with Keycloak. It does not use passport, but is simply call the OpenId Connect UserInfo endpoint on Keycloak: https://openid.net/specs/openid-connect-core-1_0.html#UserInfo.

I find it very easy to add to an application, very easy to follow, and generally very well usable (comparing to an unnamed SaaS application I was using before).

async authenticate(accessToken: string): Promise<User> {
    const url = `${this.baseURL}/realms/${this.realm}/protocol/openid-connect/userinfo`;

    try {
        const response = await this.httpService.get<KeycloakUserInfoResponse>(url, {
            headers: {
                authorization: `Bearer ${accessToken}`,
            },
        }).toPromise();

        return {
            id: response.data.sub,
            username: response.data.preferred_username,
        };
    } catch (e) {
        throw new AuthenticationError(e.message);
    }
}
like image 90
davidpodhola Avatar answered Nov 07 '22 03:11

davidpodhola


I never tried it myself, but i guess i will soon. What i would do:

  1. Check out the Authentication Technique again, and especially learn how to implement the different strategies of passport in nest: https://docs.nestjs.com/techniques/authentication
  2. Take a look at the npm-package and it's documentation. The guys from passport have dedicated a whole section to OpenID: http://www.passportjs.org/docs/openid/
  3. Implement the OpenID-Strategy in nestjs - here i would just follow the docs, since they are pretty good

I hope this will maybe help you out. At the end of the day, you will have an OpenID implementation of passport with KeyCloak and can use a guard to protect your Routes / Schemes.

like image 35
waldemar_enns Avatar answered Nov 07 '22 03:11

waldemar_enns