angular2-jwt令牌无效

时间:2016-10-26 10:14:52

标签: angular jwt

所以我有一个简单的角度2 / laravel app jwt authentification支持。我有一个服务,如果jwt令牌有效或不使用angular2-jwt tokenNotExpired()函数,每次调用路由时都会验证,但此函数总是返回false,因此用户将始终重定向到登录页面。

因此,用户登录后,将从后端生成令牌并保存在本地存储上,而服务将在使用CanActivate生命周期挂钩启动任何路由之前检查令牌是否有效。

这是我到目前为止所做的:

登录组件:

   ...
            this.http.post(SERVER_URL + 'auth', body, {
                headers: headers
            }
            ).subscribe(
                data => {

                    localStorage.setItem('auth_token', data.json().token);
                    this.authHttp.get(SERVER_URL + 'auth/user', headers)
                        .subscribe(
                        data => {
                            this.store.dispatch({ type: SET_CURRENT_USER_PROFILE, payload: data.json().user });
                            localStorage.setItem('user', data.json().user);
                            this.router.navigate(['/home']);

                        },
                        err => console.log('Fehlermeldung: ' + err)
                        );

                },
...

app.module:

...
 { provide: AuthConfig, useValue: new AuthConfig({
              headerName: 'Authorization',
              headerPrefix: 'Bearer ',
              tokenName: 'auth_token',
              tokenGetter: (() => localStorage.getItem('auth_token')),
              globalHeaders: [{ 'Content-Type': 'application/json' }],
              noJwtError: true,
              noTokenScheme: true
  })},
    AuthHttp
...

auth.service: //检查JWT令牌服务

import { tokenNotExpired } from 'angular2-jwt';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthService  {

    loggedIn() {
    return tokenNotExpired();
    }

}

auth.guard.service:

// Check if the Token of the user is still valid
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
import { AppState } from '../shared/interfaces';
import { SET_CURRENT_USER_PROFILE } from '../shared/state.actions';



import { Store } from '@ngrx/store'

@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(private auth: AuthService, private router: Router, private store: Store<AppState>) {}

  canActivate() {
    if(this.auth.loggedIn()) {
      return true;
    } else {
        console.log ('Token expired or not valid')
        localStorage.setItem('auth_token', '');
        localStorage.setItem('user', '');
        this.store.dispatch({ type: SET_CURRENT_USER_PROFILE, payload: null });
        this.router.navigate(['/']);
      return false;
    }
  }
}

app.routing:

const routes: Routes = [
  { path: 'home', component: HomeComponent},
  { path: 'about', component: AboutComponent, canActivate: [AuthGuardService]},
  { path: 'profile/:id', component: ProfileComponent, canActivate: [AuthGuardService]},
  { path: '', component: LoginComponent}
];

编辑:从后端开始,一切正常,因为在用户登录后生成令牌并存储在localstorage中。

4 个答案:

答案 0 :(得分:2)

由于属性名称,它假定它是&#34;标记&#34;。因此,当您将属性名称作为第一个参数提供时,它将正常工作。

例如:

&#13;
&#13;
tokenNotExpired('auth_token')
&#13;
&#13;
&#13;

有关此事的更多信息,请点击此处: https://github.com/auth0/angular2-jwt/issues/334

答案 1 :(得分:1)

解决方案:所以这就是我为每个可能遇到同样问题的人修复它的方法,我使用了JWTHelper函数isTokenExpired()而不是tokenNotExpired,我反转了服务中的逻辑,但是它并不能确定原因,但是

auth.service现在看起来像这样:

@Injectable()
export class AuthService  {

    private jwtHelper: JwtHelper = new JwtHelper();
    private token = localStorage.getItem('auth_token');

    isExpired() {
        return this.jwtHelper.isTokenExpired(this.token);
    }

}

和auth.guard.service canActivate():

  canActivate() {
    if (this.auth.isExpired()) {
        console.log (this.auth.isExpired());
        localStorage.setItem('auth_token', '');
        localStorage.setItem('user', '');
        this.store.dispatch({ type: SET_CURRENT_USER_PROFILE, payload: null });
        this.router.navigate(['/']);
      return false;
    } else {
      return true;
    }
  }

答案 2 :(得分:0)

`localStorage.setI`tem('id-token',token);

用于将令牌保存到本地存储/会话存储的相同令牌名称 可以作为参数传递给

return tokenNotExpired('id-token');

答案 3 :(得分:0)

将令牌作为参数传递。

更改

loggedIn() {
  return tokenNotExpired();
}

loggedIn() {
  return tokenNotExpired('id_token');
}