简体   繁体   English

如何在 NestJS 中正确使用 keycloak

[英]How to use keycloak with NestJS properly

I need to use keycloak with NestJS and GrapphQL (type-graphql).我需要在 NestJS 和 GraphQL (type-graphql) 中使用 keycloak。 There are some guides for using it with pure Express, but I'd prefer using with NestJS auth pattern.有一些使用纯 Express 的指南,但我更喜欢使用 NestJS 身份验证模式。 Can someboby give any suggestion?有人可以给任何建议吗?

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再次查看Authentication Technique,特别是学习如何在nest中实现passport的不同策略: https : //docs.nestjs.com/techniques/authentication
  2. Take a look at the npm-package and it's documentation.查看 npm-package 及其文档。 The guys from passport have dedicated a whole section to OpenID: http://www.passportjs.org/docs/openid/护照中的人专门为 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在 nestjs 中实现 OpenID-Strategy - 在这里我只会按照文档进行操作,因为它们非常好

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.在一天结束时,您将使用 KeyCloak 实现 Passport 的 OpenID 实现,并且可以使用警卫来保护您的路线/方案。

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 .这是一个老问题,但由于我刚刚完成了它,我想指出一个很棒的教程使用 Keycloak 保护您的 NestJS API 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 .它不使用passport ,而只是调用 Keycloak 上的 OpenId Connect UserInfo 端点: 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).我发现它很容易添加到应用程序中,很容易遵循,而且通常非常好用(与我之前使用的未命名的 SaaS 应用程序相比)。

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM