Why token has null value in login authentication? Angular

Published

I’m trying to write login page for my website using JWT. I’m new to Angular so I’m not even sure where might be the problem. I receive null (or undefinded) value of token, even though when I print it in concole it is actuall string.

This is my UserService.ts.

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { serializeNodes } from '@angular/compiler/src/i18n/digest';
import { tap } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class UserService {

  baseurl = "http://127.0.0.1:8000";
  httpHeaders = new HttpHeaders({'Content-Type':'application/json'});
  constructor(private http: HttpClient) { }

  login(username, password): Observable<any>{
    //console.log(this.http.post(this.baseurl + '/api/v1/rest-auth/login/', {username, password}));
    //return this.http.post(this.baseurl + '/api/v1/rest-auth/login/', {username, password});
   return this.http.post<{token:  string}>(this.baseurl + '/api/v1/rest-auth/login/', {username, password}).pipe(
     tap(
       res => {
    localStorage.setItem('token', JSON.stringify(res.token));
    }))

  }
  register(email:string, password:string) {
    return this.http.post<{token: string}>(this.baseurl + '/api/v1/rest-auth/register/', {email, password}).pipe(tap(res => {
    this.login(email, password)
  }))
  }

  logout() {
    localStorage.removeItem('token');
  }

  public get loggedIn(): boolean{
    return localStorage.getItem('token') !==  null;
  }

  getToken(){
    return localStorage.getItem('token');
  }

I know there should be JSON.parse method in getToken, but when I used it I got this error

SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at UserService.getToken (user.service.ts:40)
    at JwtService.intercept (jwt.service.ts:16)
    at HttpInterceptorHandler.handle (http.js:1258)
    at HttpXsrfInterceptor.intercept (http.js:1895)
    at HttpInterceptorHandler.handle (http.js:1258)
    at HttpInterceptingHandler.handle (http.js:1945)
    at MergeMapSubscriber.project (http.js:1082)
    at MergeMapSubscriber._tryNext (mergeMap.js:44)
    at MergeMapSubscriber._next (mergeMap.js:34)

JWTService.ts

import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { UserService } from './user.service';

@Injectable({
  providedIn: 'root'
})
export class JwtService implements HttpInterceptor{

  constructor(private injector: Injector) { }

  intercept(req, next){
    let serv = this.injector.get(UserService)
    let tokenizedReq = req.clone({
      setHeaders: {
        Authorization: `Bearer ${serv.getToken()}` 
      }
    })
    return next.handle(tokenizedReq)
  }
}

Login.component.ts

import { Component, OnInit,EventEmitter, Output } from '@angular/core';
import { User } from 'src/app/models/user';
import { Router, ActivatedRoute } from '@angular/router';
import { UserService } from './../../services/user.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  providers: [UserService]
})
export class LoginComponent implements OnInit {

  username = '';
  password = '';
  constructor(private api:UserService, private router: Router) { }
  StudentLogin = false;
  DeanLogin = false;
  AdminLogin = false;
  token = "";
  ngOnInit(): void {
  }

  showStudentLogin(){
    this.StudentLogin = true;
    this.DeanLogin = false;
    this.AdminLogin = false;
  }

  login(){
    this.api.login(this.username, this.password).subscribe(
      response => {
        this.token = response;
        console.log(response);
        alert(response)
        this.router.navigate(['/student'])
        console.log(this.api.loggedIn)
      },
      error =>{
        console.log("nie ok");
        console.log(error)
      }
    );
  }

}

app.modules.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/layout/header/header.component';
import { NavigationComponent } from './components/layout/navigation/navigation.component';
import { LoginComponent } from './components/login/login.component';
import { StudentComponent } from './components/student/student.component';
import { DeanComponent } from './components/dean/dean.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AdminComponent } from './components/admin/admin.component';
import { FormsModule } from '@angular/forms';
import { JwtModule } from '@auth0/angular-jwt';
import { JwtService } from './services/jwt.service';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    NavigationComponent,
    LoginComponent,
    StudentComponent,
    DeanComponent,
    AdminComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtService,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

I dont’t even know what to look for. Alert in login.component.ts returns response as object Object.

Source: Angular Questions

Published
Categorized as angular, jwt, jwt-auth, typescript Tagged , , ,

Answers

Resolved.
Mistake was in login function in UserService. This line should look like this:
localStorage.setItem('token', res.key);

I will leave it here in case someone has the same problem.


Dr. Antonia Lind

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Still Have Questions?


Our dedicated development team is here for you!

We can help you find answers to your question for as low as 5$.

Contact Us
faq