Coder Social home page Coder Social logo

auth0-samples / auth0-angular-samples Goto Github PK

View Code? Open in Web Editor NEW
280.0 40.0 456.0 7.58 MB

Auth0 Integration Samples for Angular 2+ Applications

Home Page: https://auth0.com/docs/quickstart/spa/angular2

License: MIT License

TypeScript 55.41% JavaScript 10.18% HTML 31.44% CSS 0.83% Dockerfile 1.55% Shell 0.32% PowerShell 0.27%
quickstart auth0 authentication angular spa dx-sdk-quickstart

auth0-angular-samples's Introduction

Auth0 Angular Samples

CircleCI

These samples demonstrate how to add authentication to an Angular application with Auth0, using auth0-angular. Each folder contains a distinct application so that various Auth0 features can be viewed in isolation. You can read about these examples in our Angular Quickstart.

Read the full tutorials on Auth0.com.

Embedded Integration Samples

These samples use Auth0's universal login page which offers the fastest, most secure, and most feature-rich way to add authentication to your app.

What is Auth0?

Auth0 helps you to:

  • Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, among others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when and where users are logging in.
  • Pull data from other sources and add it to the user profile, through JavaScript rules.

Create a free Auth0 account

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub or Microsoft Account to login.

Auth0 Configuration for the Sample Application(s)

The example application(s) require to be configured with your Auth0 information in order to run succesfully. This can be done by renaming auth_config.json.example (https://github.com/auth0-samples/auth0-angular-samples/blob/main/Sample-01/auth_config.json.example) to auth_config.json and replacing {DOMAIN}, {CLIENT_ID} and {API_IDENTIFIER} with your tenant specific values:

{
  "domain": "YOUR_DOMAIN",
  "clientId": "YOUR_CLIENT_ID",
  "authorizationParams": {
    "audience": "YOUR_API_IDENTIFIER",
  },
  "apiUri": "http://localhost:3001",
  "appUri": "http://localhost:4200"
}

Domain and Client Id can be found in the corresponding Application in the Auth0 Dashboard, while Audience needs to be set to the identifier of the API, found in the Auth0 Dashboard.

Also ensure the Application in Auth0 is configured to allow http://localhost:4200 as a Callback URL, Logout URL and Allowed Web Origin.

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Author

Auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.

auth0-angular-samples's People

Contributors

aaguiarz avatar adamjmcgrath avatar adrianchia avatar albertoperdomo avatar alexisluque avatar angularcasts-io avatar chenkie avatar cocojoe avatar cwmrowe avatar damieng avatar danoncall avatar dependabot[bot] avatar eddiejaoude avatar evansims avatar ewanharris avatar frederikprijck avatar jimmyjames avatar jmangelo avatar joshcanhelp avatar kevinsschmidt avatar kmaida avatar ksaifullah avatar lbalmaceda avatar luisrudge avatar paulioceano avatar peterblazejewicz avatar seiyria avatar snyk-bot avatar stefh avatar widcket avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth0-angular-samples's Issues

outdated auth0.js version

03-User-Sessions sample is using auth0.js v8.0.0-beta.3, other samples using auth0.js v8.0.0, when up-to-date version is 8.1.3. (AUTH-3767)

Uncaught Error: Can't resolve all parameters for AuthService: (?).

I have this very confusing error and I have no idea what to ask google.
I am using auth0 on an angular + rails app to help with authentication between a Shopify App in Rails and the front end of the app in Angular, I am using webpacker. The rails app currently works with Shopify but we are currently working a separate interface on the front end in angular in.
When I remove AuthService from the providers array in app modeul everything works fine.
But when AuthService is available in providers array, I am getting this error:
My AuthService is exactly same as what I found in the documentation and git commit.

Please help me out.
Here's what my AuthService parameters look like:

auth0 = new auth0.WebAuth({
    clientID: AUTH_CONFIG.clientID,
    domain: AUTH_CONFIG.domain,
    responseType: 'token id_token',
    audience: `https://${AUTH_CONFIG.domain}/userinfo`,
    redirectUri: 'http://localhost:5000/callback',
    scope: 'openid'
  });

Currently, when I authenticate with Rails, Everything works fine. But once we work the redirect to angular app. The session is lost.
How can we get the session parameters/request parameters from rails in my angular 4 app.

Rxjs version throws error when navigating

The rxjs version from the package is outdated as i uses 5.4.2 this throws an error "EmptyError: no elements in sequence"
when navigating to profile and other sections.
update package.json to latest 5.5.4 seems to solve the issue

Not able to access user_metadata through profile component

I'm able to access a few of the user attributes such as the picture:
<img src="{{profile?.picture}}" class="profile-avatar-lg">
But when I try and get any of the user_metadata:
<h2 class="p-b-10">{{ profile?.user_metadata.first_name }} {{ profile?.user_metadata.last_name }}</h2>
I get an error:
ERROR TypeError: Cannot read property 'first_name' of undefined

Is my syntax wrong?

Usage of scope 'openid profile' is not recommended.

   auth0 = new auth0.WebAuth({
    clientID: 'cli_id'
    domain: 'foo.auth0.com',
    responseType: 'token id_token',
    audience: 'https://foo.auth0.com/userinfo',
    redirectUri: 'http://localhost:4200/callback',
    scope: 'openid profile'
  });

Writes out warning Usage of scope 'openid profile' is not recommended. See https://auth0.com/docs/scopes for more details. to the console.

In the referred url I didn't find anything specific for this.

Any idea what is the reason behind this warning?

Thank you

04-Authorization fails to compile

04-Authorization compile ends with errors:
ERROR in src/app/admin/admin.component.ts(22,8): error TS2339: Property 'map' does not exist on type 'Observable'.
src/app/auth/auth.service.ts(17,27): error TS2339: Property 'apiUrl' does not exist on type 'AuthConfig'.
src/app/ping/ping.component.ts(25,24): error TS2339: Property 'json' does not exist on type 'Object'.
src/app/ping/ping.component.ts(40,24): error TS2339: Property 'json' does not exist on type 'Object'.

Similar story for 03-calling-an-api

Doesn't anyone update these examples? Most of them have never worked since the 4 years I have been checking in on Auth0. You would think by now they would be perfect. Far from it.

Lock version outdated

Lock version is outdated on the following sections:

  • 01-login
  • 03-session-handling
  • 04-user-profile
  • 05-linking-accounts
  • 06-rules
  • 07-authorization
  • 09-mfa
  • 10-customizing-lock

In the index.html file, as shown on the followind picture:
image

Also, on the README.md file as shown here:
image

The latest version is V10.14.

Ticket: AUTH-3348

outdated dependencies

(AUTH-4126)
Samples using outdated version of @angular/*, auth0-js, rxjs and other dependencies.

Login error

When I'm trying to log in using username-password-authentication, I received 401 Unauthorized, but I'm sure that credentials is correct.
image
Also when I'm trying to use google-oauth2 connection, it logs my Success login with different email but in reality nothing happens, I'm still having You are not logged in! Please Log In to continue. (other social connections works simmilar, logs my Success login, but nothing happens on client)
image

Cannot match any routes. URL Segment: 'access_token'

I pretty much followed the entire quickstart/login part of Angular2+ Auth0, and stopped at the part where it says that This example assumes you are using the default Angular path-based routing. If you are using hash-based routing with { useHash: true }, you will not be able to specify a dedicated callback route. The URL hash will be used to hold the user's authentication information. I'm using a hash-based routing, so I thought we could had more info on that page, but no.

I kept following this tutorial until I had in my devtool the Error: Cannot match any routes. URL Segment: 'access_token'.

Then I just researched what I could possibly do, and found the handleAuthenticationWithHash sample, so I changed everything to match it.

Unfortunately, the error is still here, the funny part is I still have the correct access_token and id_token in my localStorage, and when refreshing, my login button disappear so I'm basically logged in, what am I possibly doing wrong ?

Edit :

I'm using auth0-js 8.10.1, augnlar 4.2.4 and angular-cli 1.4.2

01-Login sample update

I've to change a code in 01 sample that way:

diff --git a/01-Login/src/app/auth/auth.service.ts b/01-Login/src/app/auth/auth.service.ts
index 70213f0..68fd9ff 100644
--- a/01-Login/src/app/auth/auth.service.ts
+++ b/01-Login/src/app/auth/auth.service.ts
@@ -8,14 +8,7 @@ declare var Auth0Lock: any;
 @Injectable()
 export class AuthService {
 
-  lock = new Auth0Lock(AUTH_CONFIG.clientID, AUTH_CONFIG.domain, {
-    oidcConformant: true,
-    autoclose: true,
-    auth: {
-      redirectUri: AUTH_CONFIG.callbackURL,
-      responseType: 'token id_token'
-    }
-  });
+  lock = new Auth0Lock(AUTH_CONFIG.clientID, AUTH_CONFIG.domain, {});

in order to get it working with social connectors. In fact that is a code implementation from other samples:
https://github.com/auth0-samples/auth0-angularjs2-systemjs-sample/blob/master/01-Login/app/auth.service.ts#L11

Otherwise it does not work with Lock, was this intended?

Components initialized twice after login

Hi. When I'm run sample "02-User-Profile" I have noticed, that CallbackComponent and HomeComponent initialized twice after login. I can't understand this strange behavior.
image

Loads of Nonce tokens in Local Storage

Hi,

Is there a safe time to clear Nonce tokens from local storage? I've got a bit of a build up of them.

Can the request+response remove them after its used?

Thanks,
Chris

http://localhost:3000/#/access_token

There is still an issue on the { useHash: true } parameter with angular 2+, I was wondering if you have a workaround for this case or a next release will fix this issue.

The callback is redirecting to that page due to hash routing in angular.

Login successfully while redirect to callback page --> Cannot match any routes. URL Segment: 'access_token'

Hello, I am following the official and current git repository to try performing the login with auto0, while my login authorization was successfully verified then there is some error happened when redirect back to my callback component.
Error Description: Cannot match any routes. URL Segment: 'access_token'

I've done a lot of research on that that I tried to use some other work around method like "handleRedirectWithHash" or "handleAuthenticationWithHash" in suggested fix while I am still getting the same error, the latest issue guides me here but it's still not solved on my end, I download the current "auth0-samples" project and run the first one "01-Login" on my local and it stucks same at the callback component so the "handleAuthentication()" method never fires.

Is there a work around documentation for resolving this issue in Auth0? Or is there any setting in Auth0 that I am missing?
I am using Angular 5.2.1 with "auth0-js": "^9.2.0" and "auth0-lock": "^11.0.1" and I am using the default Angular path-based routing.

Any suggested fix would be much appreciated!

Many thanks,
Ran

Wrong apiUrl and Audience parameter in Angular2 sample projects.

When download the Sample project, the parameter apiUrl in:
\03-calling-an-api\src\app\auth\auth0-variables.ts
\05-token-renewal\src\app\auth\auth0-variables.ts
\04-authorization\src\app\auth\auth0-variables.ts
Variable AUDIENCE in \04-authorization.env

are not propely prepopulated.

For example, I'm logged in a tenant in Australia region, and no matter how many times I reload the page, clean the cookies, close and open the windows, and download the project again, the apiUrl parameter still shows the audience from the European region tenant.

I've tried changing tenant within the same region and it appear to be ok, but when I try with my AU or US tenants, it is stuck with the EU URL.

AUTH-3348

Invalid Token Error when building app

I suddenly started getting this error when I try to npm start and build the Angular 2+ Auth0 app. I've looked in local storage and there is no token there currently. It was logging in/out fine while I was working on the mobile nav and it seems the token expired? I'm not sure how to proceed, and internet + issue searches haven't yielded any help so far. Here is the error:

AppComponent_Host.html:1 ERROR InvalidTokenError {message: "Invalid token specified", ngDebugContext: DebugContext_, __zone_symbol__currentTask: ZoneTask, ngErrorLogger: ƒ}
View_AppComponent_Host_0 @ AppComponent_Host.html:1
proxyClass @ compiler.es5.js:14971
DebugContext_.logError @ core.es5.js:13415
ErrorHandler.handleError @ core.es5.js:1080
(anonymous) @ core.es5.js:4409
webpackJsonp.1461.ZoneDelegate.invoke @ zone.js:392
webpackJsonp.1461.Zone.run @ zone.js:142
NgZone.runOutsideAngular @ core.es5.js:3844
(anonymous) @ core.es5.js:4409
webpackJsonp.1461.ZoneDelegate.invoke @ zone.js:392
onInvoke @ core.es5.js:3890
webpackJsonp.1461.ZoneDelegate.invoke @ zone.js:391
webpackJsonp.1461.Zone.run @ zone.js:142
(anonymous) @ zone.js:844
webpackJsonp.1461.ZoneDelegate.invokeTask @ zone.js:425
onInvokeTask @ core.es5.js:3881
webpackJsonp.1461.ZoneDelegate.invokeTask @ zone.js:424
webpackJsonp.1461.Zone.runTask @ zone.js:192
drainMicroTaskQueue @ zone.js:602
Promise resolved (async)
scheduleMicroTask @ zone.js:585
webpackJsonp.1461.ZoneDelegate.scheduleTask @ zone.js:414
webpackJsonp.1461.Zone.scheduleTask @ zone.js:236
webpackJsonp.1461.Zone.scheduleMicroTask @ zone.js:256
scheduleResolveOrReject @ zone.js:842
ZoneAwarePromise.then @ zone.js:932
PlatformRef_._bootstrapModuleWithZone @ core.es5.js:4537
PlatformRef_.bootstrapModule @ core.es5.js:4522
736 @ main.ts:11
__webpack_require__ @ bootstrap 80ec8132db2d6e0aedfd:52
1465 @ main.bundle.js:507
__webpack_require__ @ bootstrap 80ec8132db2d6e0aedfd:52
webpackJsonpCallback @ bootstrap 80ec8132db2d6e0aedfd:23
(anonymous) @ main.bundle.js:1
AppComponent_Host.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 1, nodeDef: {…}, elDef: {…}, elView: {…}}
View_AppComponent_Host_0 @ AppComponent_Host.html:1
proxyClass @ compiler.es5.js:14971
DebugContext_.logError @ core.es5.js:13415
ErrorHandler.handleError @ core.es5.js:1085
(anonymous) @ core.es5.js:4409
webpackJsonp.1461.ZoneDelegate.invoke @ zone.js:392
webpackJsonp.1461.Zone.run @ zone.js:142
NgZone.runOutsideAngular @ core.es5.js:3844
(anonymous) @ core.es5.js:4409
webpackJsonp.1461.ZoneDelegate.invoke @ zone.js:392
onInvoke @ core.es5.js:3890
webpackJsonp.1461.ZoneDelegate.invoke @ zone.js:391
webpackJsonp.1461.Zone.run @ zone.js:142
(anonymous) @ zone.js:844
webpackJsonp.1461.ZoneDelegate.invokeTask @ zone.js:425
onInvokeTask @ core.es5.js:3881
webpackJsonp.1461.ZoneDelegate.invokeTask @ zone.js:424
webpackJsonp.1461.Zone.runTask @ zone.js:192
drainMicroTaskQueue @ zone.js:602
Promise resolved (async)
scheduleMicroTask @ zone.js:585
webpackJsonp.1461.ZoneDelegate.scheduleTask @ zone.js:414
webpackJsonp.1461.Zone.scheduleTask @ zone.js:236
webpackJsonp.1461.Zone.scheduleMicroTask @ zone.js:256
scheduleResolveOrReject @ zone.js:842
ZoneAwarePromise.then @ zone.js:932
PlatformRef_._bootstrapModuleWithZone @ core.es5.js:4537
PlatformRef_.bootstrapModule @ core.es5.js:4522
736 @ main.ts:11
__webpack_require__ @ bootstrap 80ec8132db2d6e0aedfd:52
1465 @ main.bundle.js:507
__webpack_require__ @ bootstrap 80ec8132db2d6e0aedfd:52
webpackJsonpCallback @ bootstrap 80ec8132db2d6e0aedfd:23
(anonymous) @ main.bundle.js:1
zone.js:661 Unhandled Promise rejection: Invalid token specified ; Zone: <root> ; Task: Promise.then ; Value: InvalidTokenError {message: "Invalid token specified", ngDebugContext: DebugContext_, __zone_symbol__currentTask: ZoneTask, ngErrorLogger: ƒ} InvalidTokenError
    at Object.<anonymous> (http://localhost:4200/vendor.bundle.js:59288:31)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)
    at Object.751 (http://localhost:4200/main.bundle.js:10512:69)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)
    at Object.752 (http://localhost:4200/main.bundle.js:10584:74)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)
    at Object.736 (http://localhost:4200/main.bundle.js:10492:74)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)
    at Object.1465 (http://localhost:4200/main.bundle.js:507:18)
    at __webpack_require__ (http://localhost:4200/inline.bundle.js:53:30)

Here is my auth.service.ts file:

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

@Injectable()
export class AuthService {

  auth0 = new auth0.WebAuth({
    clientID: AUTH_CONFIG.clientID,
    domain: AUTH_CONFIG.domain,
    responseType: 'token id_token',
    audience: `https://${AUTH_CONFIG.domain}/userinfo`,
    redirectUri: AUTH_CONFIG.callbackURL,
    scope: 'openid profile'
  });

  userProfile: any;

  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);
        alert(`Error: ${err.error}. Check the console for further details.`);
      }
    });
  }

  public getProfile(cb): void {
    const accessToken = localStorage.getItem('access_token');
    if (!accessToken) {
      throw new Error('Access token must exist to fetch profile');
    }

    const self = this;
    this.auth0.client.userInfo(accessToken, (err, profile) => {
      if (profile) {
        self.userProfile = profile;
      }
      cb(err, profile);
    });
  }

  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'));
    return new Date().getTime() < expiresAt;
  }

}

Access token must exist to fetch profile

I am trying to fetch profile details after login, I get an error Access token must exist to fetch profile. This will work well without errors, if i reload the page

  ngOnInit() {
        if (this.auth.userProfile) {
          this.profile = this.auth.userProfile;
        }  
        if (this.auth.authenticated) {
            this.auth.getProfile((err, profile) => {
                this.profile = profile;
            });            
        }
    }

Error: Unsuccessful HTTP response at Request

I tried running this on my local computer and whenever I try to login I get:

Object {original: Error: Unsuccessful HTTP response at Request.<anonymous> (http://localhost:4200/vendor.bundle.js…, statusCode: 401, code: "access_denied", description: "Unauthorized"}
code
:
"access_denied"
description
:
"Unauthorized"

the error in the google console is saying:
POST https://loganborn.auth0.com/oauth/token 401 ()

Getting error for import auth0 from 'auth0-js'

src\client\app\core\services\auth.service.ts(4,19): error TS7016: Could not find
a declaration file for module 'auth0-js'. 'H:/p/node_modules/auth0-js/src/index
.js' implicitly has an 'any' type.
src\client\app\core\services\auth.service.ts(25,27): error TS7006: Parameter 'er
r' implicitly has an 'any' type.
src\client\app\core\services\auth.service.ts(25,32): error TS7006: Parameter 'au
thResult' implicitly has an 'any' type.
src\client\app\core\services\auth.service.ts(38,22): error TS7006: Parameter 'au
thResult' implicitly has an 'any' type.

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: 'B5vZn1QI60sFJnz1w_mInajQxUMl-48F',
    domain: 'phenomenex.auth0.com',
    responseType: 'token id_token',
    audience: 'https://phenomenex.auth0.com/userinfo',
    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(['/']);
      } else if (err) {
        this.router.navigate(['/']);
        console.log(err);
        alert(`Error: ${err.error}. Check the console for further details.`);
      }
    });
  }

  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'));
    return new Date().getTime() < expiresAt;
  }

}

Wrong handling of invalid fields during signup

The handling of the blank fields during user registration has three details:

  • If the password's left blank:
    image

  • Using an invalid email:
    image

  • If you put some info on the fields, then delete them before triggering signup:
    image

03-Calling-an-API: private api

Very nice tutorial, thank you.
I am getting in above example an error I can't understand. Login with auth0 works fine, I can see profile and public endpint on server works. But for the private endpoint call (Call private button in app) I am getting following error in console:

Error: getaddrinfo ENOTFOUND https https:443
    at errnoException (dns.js:50:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:91:26)

and of course the error in app:

Response with status: 500 Internal Server Error for URL: http://localhost:3001/api/private

I did try the original code from this repo and since it expect some https, I also run the server on port 443 with provided tls (works fine with public). No change for private api call altough.

Any idea where I have to look at?

Normalized User Profiles don't match with documentation

I wanted to get the user's email to display as nickname and to attach to forms on my website, but it seems that Authentication API profile is returning an object that is missing some of the members shown in the documentation.

I receive this for a profile created on the Username-Password-Authentication connection:

{
   name: "[email protected]",
   nickname: "simaadriannicolae",
   picture: "https://s.gravatar.com/...%2Favatars%2Fsi.png",
   sub: "auth0|59...6546...8c",
   updated_at: "2017-08-25T10:21:09.861Z"
}

and this for a profile created on the google-oauth2 connection:

{
    family_name: "Sima",
    gender: "male",
    given_name: "Adrian",
    locale: "en-GB",
    name: "Adrian Sima",
    nickname: "simaadriannicolae",
    picture: "https://lh6.googleuserc.../photo.jpg",
    sub: "google-oauth2|11...8313...19",
    updated_at: "2017-08-25T10:26:22.438Z"
}

But the documentation shows that I should get back something like this:

{
  "email": "[email protected]",
  "email_verified": true,
  "family_name": "Foo",
  "gender": "male",
  "given_name": "John",
  "identities": [
    {
      "provider": "google-oauth2",
      "user_id": "103547991597142817347",
      "connection": "google-oauth2",
      "isSocial": true
    }
  ],
  "locale": "en",
  "name": "John Foo",
  "nickname": "FooJon",
  "picture": "https://lh4.googleuserc.../photo.jpg",
  "user_id": "google-oauth2|103547991597142817347"
}

It seems that I am missing email, email_verified and identities, but instead I have sub.
Am I doing something wrong or has something changed to the API?
I would like to know how could I get access to "email" field from the user profile.

Migration to Angular 5

Hi,

I just upgraded to Angular 5 and I Have an "Invalid token" error now. Every thing worked find before.

Here are my packages:


  "dependencies": {
    "@agm/core": "^1.0.0-beta.0",
    "@angular/animations": "^5.1.0",
    "@angular/cdk": "^5.0.0",
    "@angular/common": "^5.1.0",
    "@angular/compiler": "^5.1.0",
    "@angular/core": "^5.1.0",
    "@angular/flex-layout": "2.0.0-beta.10-4905443",
    "@angular/forms": "^5.1.0",
    "@angular/http": "^5.1.0",
    "@angular/material": "^5.0.0",
    "@angular/platform-browser": "^5.1.0",
    "@angular/platform-browser-dynamic": "^5.1.0",
    "@angular/platform-server": "^5.1.0",
    "@angular/router": "^5.1.0",
    "@covalent/core": "^1.0.0-beta.5-1",
    "@ngui/map": "^0.20.0",
    "@ngx-translate/core": "9.0.1",
    "@ngx-translate/http-loader": "2.0.0",
    "@swimlane/ngx-charts": "7.0.1",
    "@types/googlemaps": "^3.26.13",
    "@types/node": "8.0.57",
    "angular2-jwt": "^0.2.3",
    "angular2-template-loader": "0.6.2",
    "aspnet-prerendering": "^3.0.1",
    "aspnet-webpack": "^2.0.1",
    "auth0-js": "^8.7.0",
    "auth0-lock": "^10.16.0",
    "awesome-typescript-loader": "3.4.1",
    "core-js": "^2.4.1",
    "css": "2.2.1",
    "css-loader": "0.28.7",
    "d3": "^4.4.0",
    "es6-shim": "0.35.3",
    "event-source-polyfill": "0.0.12",
    "expose-loader": "0.7.4",
    "extract-text-webpack-plugin": "3.0.2",
    "file-loader": "1.1.5",
    "hammerjs": "^2.0.8",
    "highlight.js": "9.12.0",
    "html-loader": "0.5.1",
    "isomorphic-fetch": "2.2.1",
    "jquery": "3.2.1",
    "json-loader": "0.5.7",
    "node-sass": "^4.5.3",
    "preboot": "6.0.0-beta.0",
    "raw-loader": "^0.5.1",
    "reflect-metadata": "0.1.10",
    "rxjs": "^5.2.0",
    "sass-loader": "^6.0.5",
    "showdown": "1.8.4",
    "style-loader": "0.19.0",
    "to-string-loader": "1.1.5",
    "typescript": "^2.5.3",
    "url-loader": "0.6.2",
    "web-animations-js": "2.3.1",
    "webpack": "3.10.0",
    "webpack-hot-middleware": "2.21.0",
    "webpack-merge": "4.1.1",
    "zone.js": "^0.8.12"
  },
  "devDependencies": {
    "@types/chai": "4.0.8",
    "@types/jasmine": "2.8.2",
    "@types/hammerjs": "^2.0.34",
    "chai": "4.1.2",
    "jasmine-core": "2.8.0",
    "karma": "1.7.1",
    "karma-chai": "0.1.0",
    "karma-chrome-launcher": "2.2.0",
    "karma-cli": "1.0.1",
    "karma-jasmine": "1.1.1",
    "karma-webpack": "2.0.6",
    "node-sass": "4.7.2"
  }

Here is the ts function:

public handleAuthentication(): void {
		debugger;
        this.GetAuth0(this.userInvitationId).subscribe(auth0 => {
            auth0.parseHash({ _idTokenVerification: false }, (err, authResult) => { 
                if (err) {
                    alert(`Error: ${err.errorDescription}`)
                }
                if (authResult && authResult.accessToken && authResult.idToken) {
                    localStorage.setItem('access_token', authResult.accessToken);
                    localStorage.setItem('id_token', authResult.idToken);
                    
                    this.authenticationService.authenticate(authResult.state)
                        .subscribe(result => {
                    
                            this.authentified.next(result);
                            localStorage.setItem('user', JSON.stringify(result));
                        }, error => {
                    
                            this.snackbarService.displayError(error.message);
                        });
                }
            })
        });
    }

Can you help to find the solution?

this.auth0.authorize();

I get an error here - 'Supplied parameters do not match any signature of call target.'

Where the code show function requires, options: AuthorizeOptions

Was the interface changed?

Token Renewal for same server

Hi,

I've just been playing around with the token renewal example and tried to move the silent route to the same server that hosts the main application. Is there any reason you chose to host it on another server port rather than the same one of the application?

Thanks,
Chris

Authorize Forbidden with Token Renewal example

After cloning the token renewal example (and also trying to implement it in a separate app), I get a 403 error from [domain].auth0.com/authorize?... during token renewal.

I've double and triple checked my Auth0 credentials in all files, and also have tried setting all the config over again in the renewAuth() call, but nothing has fixed this.

filter routing events by constructor.name doesn't work in production

.filter(event => event.constructor.name === 'NavigationStart')

This won't work in production mode of angular because the class name is changed.

Consider this code:

this
  .router
  .events.subscribe((e) => {
    console.log(e.constructor.name);
  });

When you run in DEV mode (ng serve), you get this:
screen shot 2017-03-23 at 19 46 40

But when you run in PROD mode (ng serve --prod), you get this:
screen shot 2017-03-23 at 19 47 22

auht0.js `parseHash` interface has been changed and samples are broken

auth0/auth0.js@3106382

This brakes both examples.

Would it be enought to PR a change like:

  constructor(private router: Router) {

    this.auth0.parseHash({
      hash: window.location.hash
    }, this.authResultCallback);
  }

  authResultCallback(error, authResult: any): void {
    if (authResult && authResult.accessToken && authResult.idToken) {
      window.location.hash = '';
      localStorage.setItem('access_token', authResult.accessToken);
      localStorage.setItem('id_token', authResult.idToken);
      this.router.navigate(['/profile']);
    } else if (authResult && authResult.error) {
      alert(`Error: ${authResult.error}`);
    }
  }

Thanks!

Improve error message in alert output

In the 00-Centralized-Login application there is an alert box with an vague error message which may be difficult to track down if you are unfamiliar with the code.

I would suggest replacing with console.log(new Error()); To make the output less disruptive to program flow and to make it easier for developers to locate where the error is being generated from.

There is one instance of this in the following location:
https://github.com/auth0-samples/auth0-angular-samples/blob/master/00-Centralized-Login/src/app/auth/auth.service.ts#L34

I assume there may be more.

HS256 not supported

authentication fails, console indicates error:
"invalid_token" "Algorithm HS256 is not supported. (Expected algs: [RS256])"

I found a workaround to this on issue: auth0/auth0.js#303

but since this is a sample app, it should work right out-of-the-box

JWT must have 3 parts

I am getting the following error and I am not quite sure how to debug/fix it. Thoughts?

Error: JWT must have 3 parts
    at JwtHelper.decodeToken (angular2-jwt.js:236) [angular]
    at JwtHelper.getTokenExpirationDate (angular2-jwt.js:246) [angular]
    at JwtHelper.isTokenExpired (angular2-jwt.js:255) [angular]
    at tokenNotExpired (angular2-jwt.js:274) [angular]
    at AuthHttp.requestWithToken (angular2-jwt.js:107) [angular]
    at DeferSubscriber.factory (angular2-jwt.js:146) [angular]
    at DeferSubscriber._callFactory (DeferObservable.js:92) [angular]
    at DeferSubscriber.tryDefer (DeferObservable.js:85) [angular]
    at new DeferSubscriber (DeferObservable.js:81) [angular]
    at DeferObservable._subscribe (DeferObservable.js:71) [angular]
    at DeferObservable.Observable._trySubscribe (Observable.js:57) [angular]
    at DeferObservable.Observable.subscribe (Observable.js:45) [angular]
    at MapOperator.call (map.js:54) [angular]
    at Observable.subscribe (Observable.js:42) [angular]

Unnecessary dependency to auth0.js library in silent.html

There's an unnecessary dependency to the auth0.js library and unnecessary configuration in the silent.html file.

The current version of the library handles it just fine if from the iFrame you just post the hash to the parent:

parent.postMessage({
      hash: window.location.hash,
      type: 'auth0:silent-authentication'
    }, 'http://localhost:4200');

#71 simplifies the silent authentication.
What do you think?

SPA Angular2 (Docker): Login Sample not running

After using sh exec.sh and show that the compilation was a success, when trying to run the sample in the browser show an error "Invalid Host header".

This happen only in the 01-Login sample.

screenshot_1
screenshot_2

00-Hosted-Login: Tests are not working

When running the tests for 00-Hosted-Login, an exception is thrown:

Chrome 57.0.2987 (Windows 8.1 0.0.0) ERROR
Uncaught Error: Zone already loaded.
at webpack:///~/zone.js/dist/zone.js:24:0 <- src/test.ts:80357

This ended up in multiple exceptions regarding invalid tests.

I've created a PR to address this.

06-Single-Sign-On - TypeError: Cannot read property 'expiresIn' of null

ERROR TypeError: Cannot read property 'expiresIn' of null
at AuthService.webpackJsonp.../../../../../src/app/auth/auth.service.ts.AuthService.setSession (auth.service.ts:62)
at auth.service.ts:97
at WebAuth.webpackJsonp.../../../../auth0-js/src/web-auth/index.js.WebAuth.parseHash (index.js:159)
at index.js:357
at IframeHandler.callback (silent-authentication-handler.js:74)
at IframeHandler.webpackJsonp.../../../../auth0-js/src/helper/iframe-handler.js.IframeHandler.eventListener (iframe-handler.js:68)
at HTMLIFrameElement.proxyEventListener (iframe-handler.js:35)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.es5.js:3881)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.