auth0-blog / angular2-authentication-sample Goto Github PK
View Code? Open in Web Editor NEWThis is a sample that shows how to add authentication to an Angular 2 (ng2) app
License: MIT License
This is a sample that shows how to add authentication to an Angular 2 (ng2) app
License: MIT License
Hi , guys I need help with some basic Issues. But I'm turning crazy trying to look for the mistake.
I'm coding a collecting data tool with angular2 in the client side and golang on the server side.
https://github.com/toni-moreno/snmpcollector/tree/add_user_login
Then adding the ts files from this sample , tsc compiler works fine but when I start the server side I realized that the angular resources are not loading with complete path
it should be "/node_modules/angular2/... /*.js"
Instead of that I'm seeing that errors.
It seems that systemjs is not able to resolve paths now.
NOTE: before importing files from https://github.com/auth0-blog/angular2-authentication-sample I was testing a hello world and works fine you can see at the master branch (https://github.com/toni-moreno/snmpcollector/tree/master/public/app)
Any help will be appreciated
The project is not compatible with 2.0.0-alpha.22, right?
Any plans to update?
I copied the files from this repo and use LoggedInOutlet.ts to setup authentication in my angular2 app, which is based on the Angular2 Webpack Starter repo.
Protected routes and login works perfectly, but the problem is that after login, the component does not initialize itself. It just loads the component but all the the Angular2 stuff like {{ somevar }} don't load, UNTIL I click on a form or click the component navigation route again. Then it initializing.
What could be causing the components to fail to load after login?
Here is my app:
http://starterhome.azurewebsites.net
I am integrating jwt_decode into existing directory but I can't solve this issue.
window.jwt_decode is not a function
I also copied the typings/_custom folder as well
On line 27 of the LoggedInOutlet you say:
if (!this.publicRoutes[url] && !localStorage.getItem('jwt')) {
So if I set my localStorage item 'jwt' to any value, I am authenticated. You are not checking, if the jwt token is valid.
Pretty simple to hack :)
Trying to use this to boilerplate a new project and I wanted to use a more current version of the beta, but things went awry:
error TS2304: Cannot find name 'Promise'
error TS2304: Cannot find name 'Map'
error TS2304: Cannot find name 'Iterator'
Angular2 is in so much flux it's hard to pin down exactly what I need to do for this to run without errors. Given I'm brand new to TS and Angular2, I could use some guidance on how to clear these errors.
Hi!
after many test I think this is the best way to redirect in LoggedInOutlet.ts.
activate(ci:ComponentInstruction)
{
let url = this.parentRouter.lastNavigationAttempt;
let route;
if (!this.publicRoutes[url] && !localStorage.getItem('jwt')) // !isAuth + !publicRoute -> Redirect to login
route = ['Login'];
else if (this.publicRoutes[url] && localStorage.getItem('jwt')) // isAuth + publicRoute -> Redirect to dashboard
route = ['Main'];
else // Continue routing without changes
{
this.parentRouter.navigateByUrl(url);
return super.activate(ci);
}
this.parentRouter.navigate(route);
return super.activate(this.parentRouter.generate(route).component);
}
This avoids to show other parts of the web.
I hope this helps.
Normal behaviour, this should route you back to /home, since you are already logged in and should only see /login when not logged in.
If I update the package version of Angular from 2.0.0-beta.0 to 2.0.0-beta.1. I get the following error when I call to the secure api through authHttp.
TypeError: First argument must be a url string or Request instance.
at Object.makeTypeError (exceptions.js:69)
at Http.request (http.js:122)
at AuthHttp._request (angular2-jwt.js:74)
at AuthHttp.requestHelper (angular2-jwt.js:83)
at AuthHttp.get (angular2-jwt.js:86)
at Home._callApi (home.ts:55)
at Home.callSecuredApi (home.ts:40)
at AbstractChangeDetector.ChangeDetector_Home_0.handleEventInternal (viewFactory_Home:173)
at AbstractChangeDetector.handleEvent (abstract_change_detector.js:57)
at AppView.triggerEventHandlers (view.js:213)
It seems there is a dependency of angular2-jwt to the older version. Is there an incompatibility between http.get in beta.0 and beta.1?.
If you look at: signup.ts, login.ts, home.ts you see the API URL is hardcoded everywhere:
http://localhost:3001/users
http://localhost:3001/sessions/create
http://localhost:3001/api/random-quote
http://localhost:3001/api/protected/random-quote
You may argue that it doesn't matter, because it's just a "sample" app and users won't be deploying it anywhere, but the truth is hardcoding API URL like this is just bad design. You should have one variable defined in a common place with the API host then use relative paths everywhere else. Otherwise the incentive is too high for the novice user to just replace localhost:3001 with their domain and build a production app with this bad practice. In fact, there already is an issue asking how to do exactly that #52 .
Hey Martin, how are you mate?
I love JWT and I try to spread its love as much as possible and this first glance of JWT with Angular 2 is awesome (still too much boilerplate, but awesome nonetheless).
That said, the signup route doesn't work and I hate when I cannot send a PR to fix it because well, I have no clue. Everything seems to be in order.
There is a typo though (PR incoming) but that doesn't fix it.
I also created a KOA backend for the demo (to practice it) and it ended really cool (I can put it on github if you want).
Gracias.
Error below:
Uncaught TypeError: change_detection_1.Pipes.extend is not a functionwebpackJsonp.273 @ pipes.ts:15__webpack_require__ @ bootstrap ec2d90a06f7e26d96c5f:71webpackJsonp.256 @ app.ts:21__webpack_require__ @ bootstrap ec2d90a06f7e26d96c5f:71webpackJsonp.255 @ bootstrap.ts:43__webpack_require__ @ bootstrap ec2d90a06f7e26d96c5f:71webpackJsonp.0 @ app.js:8__webpack_require__ @ bootstrap ec2d90a06f7e26d96c5f:71webpackJsonpCallback @ bootstrap ec2d90a06f7e26d96c5f:42(anonymous function) @ app.js:2
client?cd17:36 [WDS] Warnings while compiling.
Im getting the following error:
ORIGINAL STACK: Error: No base href set. Either provide a binding to "appBaseHrefToken" or add a base element.
I have the following RouteConfig
@RouteConfig([
{ path: '/', as: 'home', component: HomeComponent },
{ path: '/login', as: 'login', component: LoginComponent }
])
What am i doing wrong?
Do you have any plan to migrate this repo to typescript or create a separate branch for typescript?
Hi
please have a look at these modifcations:
https://github.com/frankbenoit/angular2-authentication-sample/commit/5910ed3f19a45a84e338463ac1a5cee0fc97f477
I don't know if this is a problem in my pipe usage, in the auth sample code, or in angular2?!
I added a list of text item and a pipe to 'home'.
Good cases:
Now the bad case:
Now with the pipe, not logged in and opening 'home' directly, an exception happens and
the app crashes
Can you help?
Hey guys new router has arrived and many people start using it so...
After successful Login/Logout sequence I can login again by providing the correct username together with a wrong password.
Hey I think it's time to update your app, a lot of things have changed in the last 2 months!
I run with npm start and it gives me this errors.
ERROR in multi vendor
Module not found: Error: Cannot resolve module '\SCGS001\home$\Agustin.Alberjo
\angular2-authentication-sample-master\angular2-authentication-sample-master\no
e_modules\webpack-dev-server\client\index.js' in U:\angular2-authentication-sam
le-master\angular2-authentication-sample-master
@ multi vendor
ERROR in multi app
Module not found: Error: Cannot resolve module '\SCGS001\home$\Agustin.Alberjo
\angular2-authentication-sample-master\angular2-authentication-sample-master\no
e_modules\webpack-dev-server\client\index.js' in U:\angular2-authentication-sam
le-master\angular2-authentication-sample-master
@ multi app
ERROR in .//zone.js/dist/zone.js/zone.js/dist/zone.js 1:0-160
Module not found: Error: Cannot resolve module '\SCGS001\home$\Agustin.Alberjo
\angular2-authentication-sample-master\angular2-authentication-sample-master\no
e_modules\process\browser.js' in U:\angular2-authentication-sample-master\angul
r2-authentication-sample-master\node_modules\zone.js\dist
@ ./
ERROR in .//rxjs/util/root.js/rxjs/util/root.js 1:0-158
Module not found: Error: Cannot resolve 'file' or 'directory' ./SCGS001/home$/A
ustin.Alberjon/angular2-authentication-sample-master/angular2-authentication-sa
ple-master/node_modules/webpack/buildin/module.js in U:\angular2-authentication
sample-master\angular2-authentication-sample-master\node_modules\rxjs\util
@ ./
ERROR in .//rxjs/util/Immediate.js/rxjs/util/Immediate.js 1:0-167 1:0-167
Module not found: Error: Cannot resolve module '\SCGS001\home$\Agustin.Alberjo
\angular2-authentication-sample-master\angular2-authentication-sample-master\no
e_modules\timers-browserify\main.js' in U:\angular2-authentication-sample-maste
\angular2-authentication-sample-master\node_modules\rxjs\util
@ ./
webpack: bundle is now VALID.
Can someone Help me?
@chenkie
Please update from Rc3 to RC6 or latest version in anugular2-jwt sample!!!
app.ts is different ,isn't it ?
I follow the instructions in the README (I have to change npm startwatch
to npm start
) and i get an error. This seems to be caused by part of the webpack process:
~/g/a/angular2-authentication-sample (master=) webpack
Hash: 9f6dd7034821155c451a
Version: webpack 1.11.0
Time: 3694ms
Asset Size Chunks Chunk Names
common.js 3.75 kB 0 [emitted] common
angular2.js 1.62 MB 1, 0 [emitted] angular2
app.js 324 bytes 2, 0 [emitted] app
common.js.map 3.68 kB 0 [emitted] common
angular2.js.map 1.93 MB 1, 0 [emitted] angular2
app.js.map 83 bytes 2, 0 [emitted] app
[0] multi app 28 bytes {2} [built] [1 error]
[0] multi angular2 112 bytes {1} [built] [1 error]
+ 230 hidden modules
ERROR in ./src/index.ts
Module build failed: TypeError: Cannot call method 'map' of undefined
at createService (/Users/p.smith/github/angular2-auth/angular2-authentication-sample/node_modules/typescript-simple-loader/dist/typescript-simple-loader.js:53:14)
at getLoaderInstance (/Users/p.smith/github/angular2-auth/angular2-authentication-sample/node_modules/typescript-simple-loader/dist/typescript-simple-loader.js:140:19)
at Object.loader (/Users/p.smith/github/angular2-auth/angular2-authentication-sample/node_modules/typescript-simple-loader/dist/typescript-simple-loader.js:12:14)
@ multi app
ERROR in ./src/common/BrowserDomAdapter.ts
Module build failed: TypeError: Cannot call method 'map' of undefined
at createService (/Users/p.smith/github/angular2-auth/angular2-authentication-sample/node_modules/typescript-simple-loader/dist/typescript-simple-loader.js:53:14)
at getLoaderInstance (/Users/p.smith/github/angular2-auth/angular2-authentication-sample/node_modules/typescript-simple-loader/dist/typescript-simple-loader.js:140:19)
at Object.loader (/Users/p.smith/github/angular2-auth/angular2-authentication-sample/node_modules/typescript-simple-loader/dist/typescript-simple-loader.js:12:14)
@ multi angular2
I've completely copied your schema to my project in order to provide authentication capabilities.
https://github.com/toni-moreno/snmpcollector/blob/angular2_final_migration/public/app/app.routes.ts
I'have default path to load login form
export const routes: Routes = [
{ path: '', component: Home },
{ path: './login', component: Login },
{ path: './home', component: Home, canActivate: [AuthGuard] },
{ path: '**', component: Login },
];
It loads ok , and do session creation request .
request URL:http://localhost:8090/session/create
Request Method:POST
Status Code:200 OK
stores token in LocalStorage and do this.router.navigate(['/home']);
now browser url change but nothing more happens
If I change config to first load home
import { Routes } from '@angular/router';
import { Home } from '../home/home';
import { Login } from '../login/login';
import { AuthGuard } from '../common/auth.guard';
export const routes: Routes = [
{ path: '', component: Home },
{ path: './login', component: Login },
{ path: './home', component: Home, canActivate: [AuthGuard] },
{ path: '**', component: Login },
];
it reloads ok the home page it seems like the real reload is not done. No errors in the browser console.
NOTE: I'm migrating now from angular2.0.0.-betaXXX to final release and I've updated also your authentication sample, the old version was working ok
Hi guys,
I think when the final version is released. Can we adjust the current application to be "real" that will make developers get familiar easily with angular2.
I suggest we should have a login form. Only when we pass authentication we can access Customer page for example. Otherwise should redirect to login page. And similar to Angular 1.x we have resolve in Route where we can specify some GET api to get data such as: Country, CustomerType. And these api should only work well if passed authentication.
I would like to run this program in single file. I need run two ports 3000 and 3001. These be ports necessary for sample login and authentication sample. Any sugestion?
( sorry about my english)
i think the code need a little change.
If you want to avoid a route you need to skip activation, so my propose is
We dont need to do load a route if will be avoided, so do not activate yet
activate(instruction:ComponentInstruction)
{
var url = this.parentRouter.lastNavigationAttempt;
//check in your way if the route is valid...
// is not valid
if (instruction.urlPath != 'About')
{
this.parentRouter.navigate(['/About']);
}
//is Valid
else
{
return super.activate(instruction);
}
}
After npm install I ran npm start and got following issues :
ERROR in ./src/index.ts
Module build failed: Error: Could not find the following rules specified in the configuration:
no-trailing-comma
at Object.loadRules (/angular2-authentication-sample/node_modules/tslint/lib/ruleLoader.js:29:15)
at Linter.lint (/angular2-authentication-sample/node_modules/tslint/lib/tslint.js:24:44)
at Object.lint (/angular2-authentication-sample/node_modules/tslint-loader/index.js:55:23)
at Object.module.exports /angular2-authentication-sample/node_modules/tslint-loader/index.js:139:8)
@ multi app
I believe the _custom
typings folder is confusing and troublesome. When running tsd install
it removes the _custom
folder and will install correct typings for the latest commit specified in tsd.json...which for angular2 is: DefinitelyTyped/DefinitelyTyped@e29cf4c
I think the typings setup here just needs to be cleaned up and updated to help alleviate pain here?
I'm getting the following JS error when running the app. I'm using Typescript 1.5.3
Uncaught (in promise)
Error during instantiation of Token(Promise<Compon… http://localhost:3000/build/angular2.js
WARNING in ./src/app/LoggedInOutlet.ts
[17, 1]: exceeds maximum line length of 100
ERROR in ./~/.npminstall/angular2/2.0.0-beta.17/angular2/src/core/application_ref.js
Module not found: Error: Cannot resolve module 'angular2/src/core/linker/component_resolver' in /Users/white/angular2-authentication-sample/node_modules/.npminstall/angular2/2.0.0-beta.17/angular2/src/core
@ ./~/.npminstall/angular2/2.0.0-beta.17/angular2/src/core/application_ref.js 23:27-81
webpack: bundle is now VALID.
$ node -v
v6.0.0
Hi,
Can someone let me know or give me some direction on how to unit testing on the LoggedInOutlet.ts
directive?
Any plans to add an example with social logins?
Just out of curiosity, is it your plan to keep this project up to date with new angular releases?
As a n00b it has been very helpful to see this project evolve with the various angular2 releases.
Can you please list instructions on how to edit the package.json, Procfile, etc necessary to post to Heroku. There is a limited amount of .ts / angular2 / heroku examples out there
Not 100% sure, but I cannot get this repo to work with the latest 2.0.0-alpha.29. I can't get 'Router' injected, error TS2304: Cannot find name 'Router'
When I run "npm start", I see a lot of build messages, and then it keeps hanging on "webpack: bundle is now VALID.". The build directory is not created and the server not started. What could be the issue here?
Hi friends, i think there is a issu in src/app/LoggedInOutlet.ts.
The redirect is calling twice . We need to remove the "return" statement.
We need just call super.
super.activate(instruction);
When i update angular to beta9, i got an error:
ORIGINAL EXCEPTION: Primary outlet is already registered.BrowserDomAdapter.logError @ angular2.dev.js:23597ExceptionHandler.call @ angular2.dev.js:1269(anonymous function) @ angular2.dev.js:12576NgZone._notifyOnError @ angular2.dev.js:13620collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:13524Zone.run @ angular2-polyfills.js:1247(anonymous function) @ angular2.dev.js:13543zoneBoundFn @ angular2-polyfills.js:1220lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:468lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:480lib$es6$promise$$internal$$publish @ angular2-polyfills.js:451(anonymous function) @ angular2-polyfills.js:123microtask @ angular2.dev.js:13575Zone.run @ angular2-polyfills.js:1243(anonymous function) @ angular2.dev.js:13543zoneBoundFn @ angular2-polyfills.js:1220lib$es6$promise$asap$$flush @ angular2-polyfills.js:262 angular2.dev.js:23597 ORIGINAL STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:23597ExceptionHandler.call @ angular2.dev.js:1272(anonymous function) @ angular2.dev.js:12576NgZone._notifyOnError @ angular2.dev.js:13620collection_1.StringMapWrapper.merge.onError @ angular2.dev.js:13524Zone.run @ angular2-polyfills.js:1247(anonymous function) @ angular2.dev.js:13543zoneBoundFn @ angular2-polyfills.js:1220lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:468lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:480lib$es6$promise$$internal$$publish @ angular2-polyfills.js:451(anonymous function) @ angular2-polyfills.js:123microtask @ angular2.dev.js:13575Zone.run @ angular2-polyfills.js:1243(anonymous function) @ angular2.dev.js:13543zoneBoundFn @ angular2-polyfills.js:1220lib$es6$promise$asap$$flush @ angular2-polyfills.js:262
License has to be the Auth0 MIT license because this is a public repo.
Also the readme has to include the issue reporting, author and license sections.
Why in 2.0.0-beta.17 I can not use anymore custom layouts for router-outlet? I get an error if I want to change the layout in application. For example:
<div class="guest-layout" *ngIf="auth.isGuest">
<router-outlet></router-outlet>
</div>
<div class="member-layout" *ngIf="auth.isMember">
<router-outlet></router-outlet>
</div>
When they should change, I get:
angular2.dev.js?v=1.0.0:25644 Error: Primary outlet is already registered.
at new BaseException (angular2.dev.js?v=1.0.0:5496)
at e.t.registerPrimaryOutlet (router.min.js?v=1.0.0:3)
at RouterDirective.t (router.min.js?v=1.0.0:2)
at new RouterDirective (router.js:26)
Maybe there are another ways of doing this?
any plans to update to RC6 version
Last issue, I promise :P
I am trying to understand the last piece of this puzzle so here I go:
bootstrap(App, [
bind(Router).toValue(new RootRouter(new Pipeline())),
bind(PipeRegistry).toValue(new PipeRegistry(pipes))
]);
I think that I understand the second parameter as new injections, but seems to be like new injections for the App
component itself. How does this work? Does angular (as today) need the router to be injected in that way? And what about the Pipe stuff? I know it is to add a new "filter", but why do we need to add it in the bootstrap?
While signing a token with jsonwebtoken you guys omitted the password. Is there any specific reason to do so(i.e security concern)?
Is there any article in mind for this repository? I see one for the react + auth.
If not, I could tackle it for angular-tips. I want to start talking about angular 2 ASAP for my blog and I you know I really like JWT stuff.
Of course I would give the link and credits to this repo.
My plan is to explain a bit how Angular 2 works and build this app step by step.
Cheers.
Hi,
the typescript version works perfectly. Thanx.
Coul you provide a gulpfile or is there a way to tell webpack to actually generate the "real" files.
In order to be able to deploy to an apache or nginx server.
thx.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.