ferrerojosh / nest-keycloak-connect

keycloak-nodejs-connect module for Nest
MIT License
318 stars 123 forks source link

Question: What's the easiest way to get JWT data in unprotected endpoints? #160

Closed andymel123 closed 6 months ago

andymel123 commented 1 year ago

My (simplified) use case: I have an endpoint that can be used both with and without being logged in. If the user is not logged in, I use "anonymous" as username otherwise I want to retrieve the username from the token.

Example:

@Public()
async create(@AuthenticatedUser() jwtData: any): Promise<...> {

  const username = jwtData == null ? 'anonymous' : jwtData...;
  ...
}

Is there a "nest-keycloak-connect way" of getting the JWT data in public endpoints? In the above construct (@ Public and @AuthenticatedUser() combined) the user is always undefined as the auth.guard is skipped.

I could read and parse the token myself but it would be more consistent to use nest-keycloak-connect to do it.

Any recommendation to fulfill the use case without re-writing the code? Seems like the specific logic in the library is not exported/public.

andymel123 commented 6 months ago

I am still interested in getting an answer here :)

ferrerojosh commented 6 months ago

You can pass a boolean of false in the @Public decorator.

@Public(false)
async create(@AuthenticatedUser() jwtData: any): Promise<...> {

  const username = jwtData == null ? 'anonymous' : jwtData...;
  ...
}