Quantcast
Channel: Ionic Forum - Latest topics
Viewing all articles
Browse latest Browse all 70448

Authenticating Node API & Ionic 4 with passport-jwt not working

$
0
0

@Youtaka wrote:

I’m building a mobile application with Ionic 4, with a Node API. But I have a problem with the authentication. I do this with passport-jwt, like here for example :

championshipRouter.put('/subscribe/:id', this.passport.authenticate('jwt', { session: false }), (req, res) => {
    if (!req.params || !req.params.id) { sendBodyError(res, 'No param provided'); }

    registerOrUnsubscribeToTheChampionship(req.user._id, req.params.id)
    .then( apiRes => sendApiSuccessResponse(res, 'Player has been added to the championship', apiRes) )
    .catch( apiErr => sendApiErrorResponse(res, 'Error during adding', apiErr) )
});

Everything works when I’m testing on Postman, but not with the front in Ionic 4.

In my login controller, I passed the token in my user object, then I got and stored it in my local storage like this in my login-page.component.ts :

  public login = () => {
    this.AuthService.login( this.form.value.email, this.form.value.password )
    .then( apiResponse => {
        console.log(apiResponse);
        if (apiResponse.data.countConnection == 0) {
          this.Router.navigate(['/tutorial']);
        } else {
          this.Router.navigate(['/']);
        }
        console.log(apiResponse.data.token);
        this.Storage.set('access_token', apiResponse.data.token);
        this.UtilsService.flashMessage('success', 'Vous vous êtes connecté avec succès !');
      })
    .catch( apiResponse => {
      console.error(apiResponse);
      this.UtilsService.flashMessage('error', 'L\'identifiant ou le mot de passe sont incorrects.');
    })
  }

After that, when I need to be connected to do an action, I got the token to set in my headers like that - championship.service.ts :

  public registerOrUnsubscribeToTheChampionship = (itemId: String): Promise<any> => {
    let store = this.Storage.get('access_token');

    return store.then(data => {
      this.token = data;
      let myHeader = new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.token}`
      })


      return this.HttpClient.put( this.apiUrl + '/subscribe/' + itemId, null, { headers: myHeader } )
      .toPromise()
      .then( apiResponse => Promise.resolve(apiResponse) )
      .catch( apiResponse => Promise.reject(apiResponse) );
    });
  } 

When I want to do this action in my application, I have a 401 unauthorized error, however, the token is in my header when I’m checking data.

I tried to take the Bearer token available in my Postman, but I have the same problem so I suggested that the error is not here…

If you want to check my files, I past my github repository here : https://github.com/florianrambur/PvP

Do you have any idea about that ? I tried many things but I don’t understand my error.

Thank you !

EDIT : I’m just checking something. In my login controller, I deleted this line when I’ve switch between Angular to Ionic :

res.cookie("OTPBDtoken", user.generateJwt(), { httpOnly: true });

And I added the token in my resolve object like this :

resolve({
    _id: user._id,
    pseudo: user.pseudo,
    email: user.email,
    parameters: user.parameters,
    countConnection: user.countConnection,
    token: user.generateJwt()
})

I think the problem is here, the token seems to be wrong now.

Posts: 1

Participants: 1

Read full topic


Viewing all articles
Browse latest Browse all 70448

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>