Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while using the Auth0 spa quickstart

I'm currently working on an Angular 2 web app that will use Auth0 for user authentication.

I followed the quickstart at the Auth0 website, but I'm getting the error Cannot read property 'WebAuth' of undefined at new AuthService (auth.service.ts:9), even though AuthService is declared.

Am I missing something? Any help is very much appreciated.

This is my code

//app.component.ts

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

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {

    constructor(public auth: AuthService) {
        auth.handleAuthentication();
    }
}

//auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import 'rxjs/add/operator/filter';
import auth0 from 'auth0-js';

@Injectable()
export class AuthService {

    auth0 = new auth0.WebAuth({
        clientID: '*****',
        domain: '*****',
        responseType: 'token id_token',
        audience: '******',
        redirectUri: 'http://localhost:4200/callback',
        scope: 'openid'
    });

    constructor(public router: Router) { }

    public login(): void {
        this.auth0.authorize();
    }

    public handleAuthentication(): void {
        this.auth0.parseHash((err, authResult) => {
            if (authResult && authResult.accessToken && authResult.idToken) {
                window.location.hash = '';
                this.setSession(authResult);
                this.router.navigate(['/home']);
            } else if (err) {
                this.router.navigate(['/home']);
                console.log(err);
            }
        });
    }

    private setSession(authResult): void {
        // Set the time that the access token will expire at
        const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
        localStorage.setItem('access_token', authResult.accessToken);
        localStorage.setItem('id_token', authResult.idToken);
        localStorage.setItem('expires_at', expiresAt);
    }

    public logout(): void {
        // Remove tokens and expiry time from localStorage
        localStorage.removeItem('access_token');
        localStorage.removeItem('id_token');
        localStorage.removeItem('expires_at');
        // Go back to the home route
        this.router.navigate(['/']);
    }

    public isAuthenticated(): boolean {
        // Check whether the current time is past the
        // access token's expiry time
        const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
        if (new Date().getTime() < expiresAt) {
            return true;
        } else {
            return false;
        }
    }

}

//app.html

<nav class="navbar navbar-default">
    <div class="container-fluid">
        <div class="navbar-header" *ngIf="auth" >
            <a class="navbar-brand" href="#">Auth0 - Angular</a>

            <button class="btn btn-primary btn-margin"
                    routerLink="/">
                Home
            </button>

            <button class="btn btn-primary btn-margin"
                    *ngIf="!auth.isAuthenticated()"
                    (click)="auth.login()">
                Log In
            </button>

            <button class="btn btn-primary btn-margin"
                    *ngIf="auth.isAuthenticated()"
                    (click)="auth.logout()">
                Log Out
            </button>

        </div>
    </div>
</nav>

<main class="container">
    <router-outlet></router-outlet>
</main>

Thank you

like image 979
Ana Avatar asked May 24 '17 13:05

Ana


People also ask

How can I tell if someone logged in Auth0?

The SPA SDKs have getTokenSilently which performs a silent authentication in a hidden iframe to check if the user has a valid session. If they do, tokens will be returned, if they have been logged out, you will get a “Login required” error which would indicate the user no longer has a session with Auth0.

What is Auth0 authentication?

Auth0 is a flexible, drop-in solution to add authentication and authorization services to your applications. Your team and organization can avoid the cost, time, and risk that come with building your own solution to authenticate and authorize users.


2 Answers

Have you tried to import it this way:

import * as auth0 from 'auth0-js';

like image 144
null canvas Avatar answered Oct 30 '22 22:10

null canvas


I can't see any mistake or typo. Did you do the

# installation with npm npm install --save auth0-js

and the import with:

<script type="text/javascript" src="node_modules/auth0-js/build/auth0.js"></script>

in the index.html or if you use angular-cli in the .angular-cli.json under ["app"]["scripts"]?

{ "project": { "version": "1.0.0-beta.24", "name": "angular-src" }, "apps": [{ "scripts": [ "../node_modules/jquery/dist/jquery.min.js", "../node_modules/bootstrap/dist/js/bootstrap.min.js", --> INSERT HERE <-- ],

like image 44
Ma Kobi Avatar answered Oct 30 '22 22:10

Ma Kobi