Alex D
Alex D

Reputation: 828

Angular5 Auth Token

I am working on wiring up angular front end to communicate with an API backend. The first thing I am going to do is complete the login auth. I am trying to set the token into local storage and I am not sure where I am going wrong. I keep getting a 400 bad gateway error.

auth.service console.log(res) does in back return the json response I expect from the api.

@Injectable()
export class AuthService {

  private BASE_URL: string = 'http://127.0.0.1:8000/rest-auth';
  private headers: HttpHeaders = new HttpHeaders({'Content-Type': 'application/json'});

  constructor(private http: HttpClient) {}

  login(user: LoginReponse): Promise<any> {
    let url: string = `${this.BASE_URL}/login/`;

    let headers = new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    });
    return this.http.post(url, user, {headers: this.headers}).toPromise()
      .then(
        res => console.log(res)
      );
  }

login.component

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  private TOKEN_KEY = 'id_token';
  public loginResponse: any = new LoginReponse()

  constructor(
    private auth: AuthService,
    private router: Router
  ) {

  }

  onLogin(): void {
    console.log('log user');
    this.auth.login(this.loginResponse)
      .then((loginResponse) => {
        localStorage.setItem('token', loginResponse.data.token);
        console.log('got past localstorage');
      })
      .catch((err) => {
        // console.log(err);
        console.log();
      });
  }
}

class

export class LoginReponse {
  token: string;
  user: {
    pk: number;
    username: string;
    email: string;
    first_name: string;
    last_name: string;
  };
}

Upvotes: 1

Views: 483

Answers (2)

Nolan Walker
Nolan Walker

Reputation: 352

I would suggested looking into your CORS settings on your backend setup.Certain "cross-domain" requests, notably Ajax requests, are forbidden by default by the same-origin security policy, which could be causing the http 400 error.

I will also provided auth guard and service example code which uses Observable's over Promises, now that Observable's are probably the better choice over Promise's.

AUTH GUARD

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { AuthService } from './auth.service';
import {Observable} from "rxjs";

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private router: Router, private user: AuthService) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        // check to see if a user has a valid jwt
        if (this.user.isLoggedIn()) {
            return true; // allows user to load home component
        }

        //if not, redirect back to login page
        this.router.navigate(['/login']);
        return false;
    }
}

AUTH SERVICE

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import { HttpClientModule } from '@angular/common/http';

@Injectable()
export class AuthService {
    private errorMessge: string;

    constructor(private http: HttpClientModule, private router: Router){}

    isLoggedIn(){
        return !!localStorage.getItem('token')
    }

    logout(){
        localStorage.removeItem('token');
        this.router.navigate(['login']);
    }

    login(email: string, password: string){
        let body = { email: email, password: password };
        this.http
            .post('/auth/login', body)
            .subscribe(
                res => {
                    localStorage.setItem('token', res.token);
                    this.router.navigate(['home/profile']);
                },
                error => {
                    console.log(error);
                    this.errorMessge = error.message;
                }
            );
    }

}

Upvotes: 0

Joe Belladonna
Joe Belladonna

Reputation: 1339

I had the same problems. Please take a look here and here. There you will find how I resolved issue with preflight requests and how I did setup my angular 5 app for token usage.

If you need more help please let me know.

Upvotes: 2

Related Questions