在Auth0Lock对象中使用选项时,Angular2 Auth0令牌未被存储

时间:2016-10-16 21:05:25

标签: javascript angular typescript auth0

我正在使用Auth0来验证我的NG2应用中的用户。我设置AuthGuard以阻止用户在没有令牌的情况下访问应用程序中的某些页面。

当我使用没有任何选项的Lock小部件时,令牌会保存到localStorage而没有任何问题。但是,如果我使用这些选项,则不会将其保存到localStorage

更具体地说,我可以使用一些选项,但当我添加auth:及其参数时,令牌将不会保存到localStorage

这是导致问题的部分:

auth: { responseType: 'token', redirect: true, redirectUrl: "http://localhost/dashboard" },

将其添加到选项后,它不会将令牌保存到localStorage

档案auth.service.ts

import { Injectable }                      from '@angular/core';
import { tokenNotExpired, JwtHelper }      from 'angular2-jwt';
import { Router }                          from '@angular/router';
import { myConfig }                        from './auth.config';

declare var Auth0Lock: any;

var options = {
  theme: { logo: '../assets/img/logo.png', primaryColor: '#779476' },
  auth: { responseType: 'token', redirect: true, redirectUrl: "http://localhost/dashboard" },
  languageDictionary: { emailInputPlaceholder: "eve@example.com", title: "Login" }, 
};

@Injectable()
export class Auth {
  lock = new Auth0Lock(myConfig.clientID, myConfig.domain, options, {});

  constructor( private router: Router ) {
    this.lock.on('authenticated', (authResult) => {
      localStorage.setItem('id_token', authResult.idToken);
    });
  }

  public login() { this.lock.show(); };
  public logout() { localStorage.removeItem('id_token'); };
  public authenticated() { return tokenNotExpired(); };
}

档案guard.service.ts

import { Injectable }           from '@angular/core';
import {
    CanActivate,
    Router,
    ActivatedRouteSnapshot,
    RouterStateSnapshot
}                               from '@angular/router';
import { Auth }                 from './auth.service';
import { Observable }           from 'rxjs/Observable';

@Injectable()
export class Guard implements CanActivate {

    constructor(protected router: Router, protected auth: Auth ) {}

     canActivate() {
        if (localStorage.getItem('id_token')) {
            // logged in so return true
            return true;
        }
        // not logged in so redirect to login page
        this.router.navigate(['/pages/home']);
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

尝试在this.lock设置中更改此设置。

auth: {
    redirect:false,
  }

来源:

  • auth0.com/forum/t/authenticated-event-not-triggering/3554
  • github.com/auth0/lock/issues/527

如果您仍想坚持使用重定向功能,您可以尝试自行获取这些功能。详情请见:auth0.com/forum/t/callback-url-begins-with-hash/3694