【问题标题】:Angular2-jwt, getting empty errors in GET/POST responses when there is no JWT TokenAngular2-jwt,当没有 JWT 令牌时,在 GET/POST 响应中出现空错误
【发布时间】:2017-03-11 13:38:48
【问题描述】:

我正在实施以下教程以获得一些 Angular 基础知识: http://jasonwatmore.com/post/2016/08/16/angular-2-jwt-authentication-example-tutorial

此外,我实际上想使用“angular2-jwt”库。但是,如果本地没有保存 JWT,我使用 authHttp 发送的每个 GET 或 POST 请求都会失败,控制台中只会出现一个空错误。
“错误:login.component.html 中的错误由以下原因引起:”

没有“没有 JWT 存在或已过期”错误文本,什么都没有。
顺便说一句,标准的 Http Class 工作正常。 “tokenNotExpired()”方法也是如此。
还尝试添加

'js-base64':'npm:js-base64/base64.js',
'buffer':'@empty'

映射到我的systemsjs.config.js的信息,还是没有结果。

知道我做错了什么吗? :(

Angular 2.1.0 + angular2-jwt 0.1.25

app.module.ts

import {NgModule} from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
import {FormsModule} from "@angular/forms";
import {HttpModule} from "@angular/http";
import {AppComponent} from "./app.component";
import {AppRoutingModule} from "./app-routing.module";
import {LoginComponent} from "./login/login.component";
import {MainComponent} from "./main/main.component";
import {AuthService} from "./services/auth.service";
import {AUTH_PROVIDERS} from "angular2-jwt";

@NgModule({
    imports: [
        BrowserModule,
        AppRoutingModule,
        FormsModule,
        HttpModule
    ],
    declarations: [
        AppComponent,
        LoginComponent,
        MainComponent
    ],
    providers: [
        AuthService,
        AUTH_PROVIDERS
    ],
    bootstrap: [AppComponent]
})
export class AppModule
{
}

login.component.ts

import { Component } from '@angular/core';
import { AuthService } from "../services/auth.service";

@Component({
    moduleId: module.id,
    templateUrl: 'login.component.html'
})

export class LoginComponent {

    user: any = {
        login: 'defaultLogin',
        password: 'defaultPassword'
    };
    errorMsg = '';

    constructor(
        private authService: AuthService) { }


    login() {
        this.authService.login(this.user.name, this.user.password)
            .subscribe(result => {

            });
    }
}

auth.service.ts

import {Injectable} from "@angular/core";
import {Response} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";
import {AuthHttp} from "angular2-jwt";

@Injectable()
export class AuthService
{
    constructor(private authHttp: AuthHttp)
    {
    }

    login(username: string, password: string)
    {
        return this.authHttp.post('/api/login', JSON.stringify({username: username, password: password}))
            .map((response: Response) =>{
                return false;
            });
    }
}

【问题讨论】:

  • 我得到了类似的东西——错误被吞没了,我得到了一个非常奇怪的异常,即 Observables 没有处理拒绝。在 JWT 库中进行一些调试后,我发现这是被抛出的:obs.error(new AuthHttpError('No JWT present or has expired'));

标签: angular jwt


【解决方案1】:

这是 angular2-jwt

的默认行为

默认情况下,如果没有保存有效的JWTAuthHttp会返回一个 可观察到的错误,带有“无效的 JWT”。如果您想继续 使用未经身份验证的请求,您可以将 noJwtError 设置为 true.

你应该只在你想要做认证请求时使用AuthHttp,所以在你的AuthService上你还需要导入Http服务,像这样:

import { Injectable } from "@angular/core";
import { Http, Response} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";
import { AuthHttp } from "angular2-jwt";

@Injectable()
export class AuthService
{
    constructor(private http: Http, private authHttp: AuthHttp){ }

    login(username: string, password: string){
      //use this.http instead of this.authHttp
      return this.http.post('/api/login', {username: username, password: password})
        .map((response: Response) => {
          return false;
        });
    }
}

如前所述,Angular2-jwt 检查有效的 JWT 令牌,如果万一没有有效的 JWT,那么它甚至不会发出请求。

但是,如果您想对每个请求使用 authHttp,您可以禁用 JWT 令牌验证,通过覆盖提供程序的配置,在您的 app.modute.ts 上添加它:

import {NgModule} from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
import {FormsModule} from "@angular/forms";
import {HttpModule} from "@angular/http";
import {AppComponent} from "./app.component";
import {AppRoutingModule} from "./app-routing.module";
import {LoginComponent} from "./login/login.component";
import {MainComponent} from "./main/main.component";
import {AuthService} from "./services/auth.service";
import { provideAuth } from 'angular2-jwt';

@NgModule({
    imports     : [
        BrowserModule,
        AppRoutingModule,
        FormsModule,
        HttpModule
    ],
    declarations: [
        AppComponent,
        LoginComponent,
        MainComponent
    ],
    providers   : [
        AuthService,
        provideAuth({
          noJwtError: true,
        })
    ],
    bootstrap   : [AppComponent]
})
export class AppModule
{
}

更多信息here

编辑:

带有错误处理程序的 AuthService:

import { Injectable } from "@angular/core";
import { Http, Response} from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";
import { AuthHttp, AuthHttpError } from "angular2-jwt"; //we need to import the AuthHttpError

@Injectable()
export class AuthService
{
    constructor(private http: Http, private authHttp: AuthHttp){ }

    login(username: string, password: string){
      //use this.http instead of this.authHttp
      return this.http.post('/api/login', {username: username, password: password})
        .map((response: Response) => {
          return false;
        })
        .catch(this.handleError); // we had the catch
    }

    private handleError (error: Response | any) {
        // In a real world app, we might use a remote logging infrastructure
        let errMsg: string;
        if (error instanceof AuthHttpError) {
          //here we will handle JWT errors
          console.log(error)
        } else if (error instanceof Response) {
          const body = error.json() || '';
          const err = body.error || JSON.stringify(body);
          errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        }else {
          errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }
}

【讨论】:

  • "将返回带有 'Invalid JWT' 的 Observable 错误" 嗯,好的,但是有没有办法得到那个 "Invalid JWT" 错误文本(实际上它必须是“没有 JWT 存在或已过期” 文本,因为我的 angular2-jwt 来源,但这并不重要)? :) 如果我从 login.component.ts (err => console.log(err)) 在 login() 方法中添加错误处理器作为第二个参数,我会收到 "Object { stack: "" }" 消息控制台。
  • 如果我尝试在我的 auth.service.ts 中处理错误(使用来自linkhandleError 方法),我只会在控制台中收到一条“错误”消息在 handleError 中调用 .toString() 方法。我在这里要做的是,我想保留默认的 noJWT-error,但我也希望有机会在我的请求中处理该错误。因为我可以想象用户应该拥有 JWT 但由于某些原因它不会在发出请求的那一刻的情况。还是我错过了什么?
  • 这是一个不同的问题,但基本上你需要稍微改变一下 handleError 函数,我编辑了我的答案,看看 handleError 函数
  • 天哪,不,我仍然无法收到该消息。 .json() 不是函数,因为 AuthHttpError 不是响应。它只是一个 { stack: "" } 对象。 AuthHttpError 扩展了具有“名称”和“消息”属性的 TS 错误类。 console.log(error.name, error.message) 当前向我显示一个空名称和“错误”消息...
  • 哦在那种情况下切换if的顺序
猜你喜欢
  • 2018-09-24
  • 2018-03-16
  • 1970-01-01
  • 2017-11-03
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 2018-05-01
相关资源
最近更新 更多