I am trying to implement a custom login in my angular 2 spa.
I used the official documentation as a guide and made sure to follow all the steps.
Angular2-jwt was successfully included in the project. I also made sure to call the handleAuthentication
method in the application’s root component.
Here is the auth.service.ts
import { Injectable } from '@angular/core';
import { tokenNotExpired } from 'angular2-jwt';
import { Router } from '@angular/router';
// Avoid name not found warnings
let Auth0Lock = require('auth0-lock').default;
var options = {
auth: {
redirect: true,
redirectUrl: "http://localhost:54435/home",
responseType: "token id_token",
},
rememberLastLogin: false
};
@Injectable()
export class Auth {
// Configure Auth0
lock = new Auth0Lock('xxx', 'xxx', options);
constructor(private router: Router) {
}
public handleAuthentication(): void {
this.lock.parseHash({ _idTokenVerification: false }, (err, authResult) => {
if (err) {
alert(`Error: ${err.errorDescription}`)
}
if (authResult && authResult.accessToken && authResult.idToken) {
window.location.hash = '';
localStorage.setItem('access_token', authResult.accessToken);
localStorage.setItem('id_token', authResult.idToken);
this.router.navigate('/home']);
}
});
}
public login(username: string, password: string) {
this.lock.redirect.loginWithCredentials({
connection: 'Username-Password-Authentication',
username,
password
}, err => {
if (err) return alert(err.description);
});
}
public authenticated() {
// Check if there's an unexpired JWT
// This searches for an item in localStorage with key == 'id_token'
return tokenNotExpired('id_token');
}
public logout() {
// Remove token from localStorage
localStorage.removeItem('access_token');
localStorage.removeItem('id_token');
}
private setUser(authResult) {
localStorage.setItem('access_token', authResult.accessToken);
localStorage.setItem('id_token', authResult.idToken);
}
}
I noticed that someone had the same issue in this thread.
The answer from @jmangelo :
“That particular page seems to be referencing an incorrect code snippet version given that the parseHash function was available in a previous version of Lock, but not in version 10.”
Is the code in the documentation outdated or is the error in my code?
The versions I’m using:
“angular2-jwt”: “^0.2.3”,
“auth0-js”: “^8.6.0”,
“auth0-lock”: “^10.14.0”
I’m willing to provide any additional information.