【问题标题】:Angular5 Auth TokenAngular5 身份验证令牌
【发布时间】:2018-04-13 19:38:18
【问题描述】:

我正在努力连接 Angular 前端以与 API 后端进行通信。我要做的第一件事是完成登录验证。我正在尝试将令牌设置到本地存储中,但我不确定我哪里出错了。我不断收到 400 bad gateway 错误。

auth.service console.log(res) 确实返回了我期望从 api 获得的 json 响应。

@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();
      });
  }
}

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

【问题讨论】:

  • 您是否为您的应用程序设置了 CORS?

标签: angular angular5


【解决方案1】:

我也有同样的问题。请查看herehere。在那里你会发现我是如何解决预检请求的问题,以及我是如何设置我的 Angular 5 应用程序以使用令牌的。

如果您需要更多帮助,请告诉我。

【讨论】:

  • 出于兴趣,你为什么使用 toPromise 而不是 observable?
  • 我到底在哪里使用了 promise?
  • }); return this.http.post(url, user, {headers: this.headers}).toPromise() 我通常不使用 toPromise 我只是使用利用 observables 的 httpclient
  • 我也不使用承诺。你确定这是我的帖子? Alex D 使用了 Promise,但如果您检查我在答案中发布的两个链接,您将不会发现使用了 Promise。
  • 我的评论确实是针对 Alex D,我想我很困惑。我以某种方式评论了您的解决方案,而不是 Alex D。抱歉。
【解决方案2】:

我建议在您的后端设置中查看您的 CORS 设置。某些“跨域”请求,尤其是 Ajax 请求,默认情况下被同源安全策略禁止,这可能会导致 http 400 错误。

我还将提供使用 Observable 而不是 Promise 的身份验证保护和服务示例代码,现在 Observable 可能是比 Promise 更好的选择。

授权保护

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;
    }
}

授权服务

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;
                }
            );
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 2019-11-24
    • 1970-01-01
    • 2017-11-08
    相关资源
    最近更新 更多