Ionic framework Django rest framework后端的Ionic2 JWT身份验证失败

Ionic framework Django rest framework后端的Ionic2 JWT身份验证失败,ionic-framework,ionic2,Ionic Framework,Ionic2,我正在构建一个Ionic 2应用程序,我正在尝试使用JWT对我的用户进行身份验证,如下所示: 单击“登录”服务器发送回我可以在开发者控制台网络中看到的令牌,但是我在控制台上遇到以下错误:(build/pages/profile/profile.html:8:29&原始异常:错误:JWT必须有3个部分。)此外,我每次都必须清除cookie 我的个人资料。ts: import {Page, Storage, LocalStorage} from 'ionic-angular'; import {Ht

我正在构建一个Ionic 2应用程序,我正在尝试使用JWT对我的用户进行身份验证,如下所示:

单击“登录”服务器发送回我可以在开发者控制台网络中看到的令牌,但是我在控制台上遇到以下错误:(build/pages/profile/profile.html:8:29&原始异常:错误:JWT必须有3个部分。)此外,我每次都必须清除cookie

我的个人资料。ts:

import {Page, Storage, LocalStorage} from 'ionic-angular';
import {Http, Headers} from '@angular/http';
import {FORM_DIRECTIVES} from '@angular/common';
import {JwtHelper} from 'angular2-jwt';
import {AuthService} from '../../services/auth/auth.service';
import 'rxjs/add/operator/map';
import { NavController, NavParams } from 'ionic-angular';

import { StartPage } from '../start/start.component';


@Page({
  templateUrl: 'build/pages/profile/profile.html',
  directives: [FORM_DIRECTIVES]
})
export class ProfilePage {
  LOGIN_URL: string = " http://127.0.0.1:8000/rest-auth/login/";
  SIGNUP_URL: string = "http://127.0.0.1:8000/rest-auth/registration/";

  auth: AuthService;
  // When the page loads, we want the Login segment to be selected
  authType: string = "login";
  // We need to set the content type for the server
  contentHeader: Headers = new Headers({"Content-Type": "application/json"});
  error: string;
  jwtHelper: JwtHelper = new JwtHelper();
  local: Storage = new Storage(LocalStorage);
  user: string;  

  constructor(private http: Http, public nav:NavController) {
    this.auth = AuthService;
    this.local.get('profile').then(profile => {
      this.user = JSON.parse(profile);
    }).catch(error => {
      console.log(error);
    });
  }

  login(credentials) {
    this.http.post(this.LOGIN_URL, JSON.stringify(credentials), { headers: this.contentHeader })
      .map(res => res.json())
      .subscribe(
        data => this.authSuccess(data.id_token),
        err => this.error = err
      );
  }

  signup(credentials) {
    this.http.post(this.SIGNUP_URL, JSON.stringify(credentials), { headers: this.contentHeader })
      .map(res => res.json())
      .subscribe(
        data => this.authSuccess(data.id_token),
        err => this.error = err
      );
  }

  logout() {
    this.local.remove('id_token');
    this.user = null;
  }

  authSuccess(token) {
    this.error = null;
    this.local.set('id_token', token);
    this.user = this.jwtHelper.decodeToken(token);

  }
}
import {tokenNotExpired} from 'angular2-jwt';

export class AuthService {
  constructor() {}

  public static authenticated() {
    return tokenNotExpired();
  }
}
<!-- app/profile/profile.html -->
  <ion-navbar *navbar>
    <button menuToggle>
    <ion-icon name="menu"></ion-icon>
  </button>
    <ion-title>Profile</ion-title>
  </ion-navbar>

  <ion-content class="login" *ngIf="!auth.authenticated()">

      <div padding>
        <ion-segment [(ngModel)]="authType">
          <ion-segment-button value="login">
            Login
          </ion-segment-button>
          <ion-segment-button value="signup">
            Signup
          </ion-segment-button>
        </ion-segment>
      </div>

      <div [ngSwitch]="authType">
        <form *ngSwitchWhen="'login'" #loginCreds="ngForm" (ngSubmit)="login(loginCreds.value)">
          <ion-item>
            <ion-label>Username</ion-label>
            <ion-input type="text" ngControl="email"></ion-input>
          </ion-item>

          <ion-item>
            <ion-label>Password</ion-label>
            <ion-input type="password" ngControl="password"></ion-input>
          </ion-item>

          <div padding>
            <button block type="submit">Login</button>        
          </div>

        </form>

        <form *ngSwitchWhen="'signup'" #signupCreds="ngForm" (ngSubmit)="signup(signupCreds.value)">
          <ion-item>
            <ion-label>Username</ion-label>
            <ion-input type="text" ngControl="username"></ion-input>
          </ion-item>

          <ion-item>
            <ion-label>Password</ion-label>
            <ion-input type="password" ngControl="password"></ion-input>
          </ion-item>

          <div padding>
            <button block type="submit">Signup</button>
          </div>

        </form>
      </div>

      <div padding>
        <p *ngIf="error" class="error">{{ error._body }}</p>  
      </div>

  </ion-content>

  <ion-content>
    <div *ngIf="auth.authenticated()">
      <div padding>
        <h1>Welcome, {{ user }}</h1>
        <button block (click)="logout()">Logout</button>
      </div>  
    </div>
  </ion-content>
我的服务:

import {Page, Storage, LocalStorage} from 'ionic-angular';
import {Http, Headers} from '@angular/http';
import {FORM_DIRECTIVES} from '@angular/common';
import {JwtHelper} from 'angular2-jwt';
import {AuthService} from '../../services/auth/auth.service';
import 'rxjs/add/operator/map';
import { NavController, NavParams } from 'ionic-angular';

import { StartPage } from '../start/start.component';


@Page({
  templateUrl: 'build/pages/profile/profile.html',
  directives: [FORM_DIRECTIVES]
})
export class ProfilePage {
  LOGIN_URL: string = " http://127.0.0.1:8000/rest-auth/login/";
  SIGNUP_URL: string = "http://127.0.0.1:8000/rest-auth/registration/";

  auth: AuthService;
  // When the page loads, we want the Login segment to be selected
  authType: string = "login";
  // We need to set the content type for the server
  contentHeader: Headers = new Headers({"Content-Type": "application/json"});
  error: string;
  jwtHelper: JwtHelper = new JwtHelper();
  local: Storage = new Storage(LocalStorage);
  user: string;  

  constructor(private http: Http, public nav:NavController) {
    this.auth = AuthService;
    this.local.get('profile').then(profile => {
      this.user = JSON.parse(profile);
    }).catch(error => {
      console.log(error);
    });
  }

  login(credentials) {
    this.http.post(this.LOGIN_URL, JSON.stringify(credentials), { headers: this.contentHeader })
      .map(res => res.json())
      .subscribe(
        data => this.authSuccess(data.id_token),
        err => this.error = err
      );
  }

  signup(credentials) {
    this.http.post(this.SIGNUP_URL, JSON.stringify(credentials), { headers: this.contentHeader })
      .map(res => res.json())
      .subscribe(
        data => this.authSuccess(data.id_token),
        err => this.error = err
      );
  }

  logout() {
    this.local.remove('id_token');
    this.user = null;
  }

  authSuccess(token) {
    this.error = null;
    this.local.set('id_token', token);
    this.user = this.jwtHelper.decodeToken(token);

  }
}
import {tokenNotExpired} from 'angular2-jwt';

export class AuthService {
  constructor() {}

  public static authenticated() {
    return tokenNotExpired();
  }
}
<!-- app/profile/profile.html -->
  <ion-navbar *navbar>
    <button menuToggle>
    <ion-icon name="menu"></ion-icon>
  </button>
    <ion-title>Profile</ion-title>
  </ion-navbar>

  <ion-content class="login" *ngIf="!auth.authenticated()">

      <div padding>
        <ion-segment [(ngModel)]="authType">
          <ion-segment-button value="login">
            Login
          </ion-segment-button>
          <ion-segment-button value="signup">
            Signup
          </ion-segment-button>
        </ion-segment>
      </div>

      <div [ngSwitch]="authType">
        <form *ngSwitchWhen="'login'" #loginCreds="ngForm" (ngSubmit)="login(loginCreds.value)">
          <ion-item>
            <ion-label>Username</ion-label>
            <ion-input type="text" ngControl="email"></ion-input>
          </ion-item>

          <ion-item>
            <ion-label>Password</ion-label>
            <ion-input type="password" ngControl="password"></ion-input>
          </ion-item>

          <div padding>
            <button block type="submit">Login</button>        
          </div>

        </form>

        <form *ngSwitchWhen="'signup'" #signupCreds="ngForm" (ngSubmit)="signup(signupCreds.value)">
          <ion-item>
            <ion-label>Username</ion-label>
            <ion-input type="text" ngControl="username"></ion-input>
          </ion-item>

          <ion-item>
            <ion-label>Password</ion-label>
            <ion-input type="password" ngControl="password"></ion-input>
          </ion-item>

          <div padding>
            <button block type="submit">Signup</button>
          </div>

        </form>
      </div>

      <div padding>
        <p *ngIf="error" class="error">{{ error._body }}</p>  
      </div>

  </ion-content>

  <ion-content>
    <div *ngIf="auth.authenticated()">
      <div padding>
        <h1>Welcome, {{ user }}</h1>
        <button block (click)="logout()">Logout</button>
      </div>  
    </div>
  </ion-content>
My profile.html:

import {Page, Storage, LocalStorage} from 'ionic-angular';
import {Http, Headers} from '@angular/http';
import {FORM_DIRECTIVES} from '@angular/common';
import {JwtHelper} from 'angular2-jwt';
import {AuthService} from '../../services/auth/auth.service';
import 'rxjs/add/operator/map';
import { NavController, NavParams } from 'ionic-angular';

import { StartPage } from '../start/start.component';


@Page({
  templateUrl: 'build/pages/profile/profile.html',
  directives: [FORM_DIRECTIVES]
})
export class ProfilePage {
  LOGIN_URL: string = " http://127.0.0.1:8000/rest-auth/login/";
  SIGNUP_URL: string = "http://127.0.0.1:8000/rest-auth/registration/";

  auth: AuthService;
  // When the page loads, we want the Login segment to be selected
  authType: string = "login";
  // We need to set the content type for the server
  contentHeader: Headers = new Headers({"Content-Type": "application/json"});
  error: string;
  jwtHelper: JwtHelper = new JwtHelper();
  local: Storage = new Storage(LocalStorage);
  user: string;  

  constructor(private http: Http, public nav:NavController) {
    this.auth = AuthService;
    this.local.get('profile').then(profile => {
      this.user = JSON.parse(profile);
    }).catch(error => {
      console.log(error);
    });
  }

  login(credentials) {
    this.http.post(this.LOGIN_URL, JSON.stringify(credentials), { headers: this.contentHeader })
      .map(res => res.json())
      .subscribe(
        data => this.authSuccess(data.id_token),
        err => this.error = err
      );
  }

  signup(credentials) {
    this.http.post(this.SIGNUP_URL, JSON.stringify(credentials), { headers: this.contentHeader })
      .map(res => res.json())
      .subscribe(
        data => this.authSuccess(data.id_token),
        err => this.error = err
      );
  }

  logout() {
    this.local.remove('id_token');
    this.user = null;
  }

  authSuccess(token) {
    this.error = null;
    this.local.set('id_token', token);
    this.user = this.jwtHelper.decodeToken(token);

  }
}
import {tokenNotExpired} from 'angular2-jwt';

export class AuthService {
  constructor() {}

  public static authenticated() {
    return tokenNotExpired();
  }
}
<!-- app/profile/profile.html -->
  <ion-navbar *navbar>
    <button menuToggle>
    <ion-icon name="menu"></ion-icon>
  </button>
    <ion-title>Profile</ion-title>
  </ion-navbar>

  <ion-content class="login" *ngIf="!auth.authenticated()">

      <div padding>
        <ion-segment [(ngModel)]="authType">
          <ion-segment-button value="login">
            Login
          </ion-segment-button>
          <ion-segment-button value="signup">
            Signup
          </ion-segment-button>
        </ion-segment>
      </div>

      <div [ngSwitch]="authType">
        <form *ngSwitchWhen="'login'" #loginCreds="ngForm" (ngSubmit)="login(loginCreds.value)">
          <ion-item>
            <ion-label>Username</ion-label>
            <ion-input type="text" ngControl="email"></ion-input>
          </ion-item>

          <ion-item>
            <ion-label>Password</ion-label>
            <ion-input type="password" ngControl="password"></ion-input>
          </ion-item>

          <div padding>
            <button block type="submit">Login</button>        
          </div>

        </form>

        <form *ngSwitchWhen="'signup'" #signupCreds="ngForm" (ngSubmit)="signup(signupCreds.value)">
          <ion-item>
            <ion-label>Username</ion-label>
            <ion-input type="text" ngControl="username"></ion-input>
          </ion-item>

          <ion-item>
            <ion-label>Password</ion-label>
            <ion-input type="password" ngControl="password"></ion-input>
          </ion-item>

          <div padding>
            <button block type="submit">Signup</button>
          </div>

        </form>
      </div>

      <div padding>
        <p *ngIf="error" class="error">{{ error._body }}</p>  
      </div>

  </ion-content>

  <ion-content>
    <div *ngIf="auth.authenticated()">
      <div padding>
        <h1>Welcome, {{ user }}</h1>
        <button block (click)="logout()">Logout</button>
      </div>  
    </div>
  </ion-content>

轮廓
登录
报名
用户名
密码
登录
用户名
密码
报名
{{error.\u body}}

欢迎,{{user}} 注销

成功登录后,我希望导航到特定页面。出了什么问题,我该如何解决

另外,我从后端返回的令牌(我在后端使用Django rest auth进行身份验证):


我认为您的后端可能有问题,看起来您的Ionic2应用程序工作正常,但您的web服务未返回有效令牌,因此抛出了一个错误。是。按照我之前评论中的链接阅读文档。