简体   繁体   中英

Authentication with google oauth and nestjs

I want to use a guard for my routes controller based on the access token of google, but I don't know how to implement this.

I retrieve this from my google oauth

{
  "message": "User information from google",
  "user": {
    "email": "test@gmail.com",
    "firstName": "John",
    "lastName": "Kennedy",
    "picture": 
    "https://lh3.googleusercontent.com/a-/mypicture",
    "accessToken": "myaccesstoken"
  }
}

Now I don't know how to use this access token for my other routes, example in a controller:

  @UseGuards() // I don't know what to put here
  @Get('/get_customer/:id')
  async findCustomerById(@Param() params): Promise<Customer> {
    try {
      return await this.stripeService.findCustomerById(params.id);
    } catch (e) {
      throw new Error(e.message);
    }
  }

Follow this article , it worked for me.

Short Answer:

Inside google's redirect endpoint, You can issue a JWT token to the user, which will hold their data as payload, and secure your endpoints with JWT verification guard. See this

Long Answer:

What google basically does is just provide your application with the identity of the user who used that service to log in... Specifically, google provides you with the user's data(with the scopes you defined) and an access token.

at this point, you have multiple approaches to guard your routes:

  1. Issue a JWT token that holds this user data you got from google and return it to the user(the client), each request the user sends with that token you would be able to identify the user and give them access to routes (stateless way: the token will hold everything encrypted inside it) See this .
  2. Store a session of this user that contains the data you got from google, and give them the SessionId that will make you(the server) identify the user later on and give them access to routes (stateful way: you need to store the session data somewhere).

You might wonder what is the use of the access token in all of this... generally, this token can only be used by your application (which has ClientId+ClientSecret you got from google) to access user's google data(defined by scopes you chose) on behalf of them. So basically this token is a consent from the user so your app can access their google data.

This, for example, can be useful if you can't store user's data in our database(for legal reasons), so you can directly query their data from google without consulting them every single time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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