[英]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:
我会怎么做:
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.