Giter Club home page Giter Club logo

angular2-jwt's People

Contributors

avatsaev avatar bdanchilla avatar charsleysa avatar chenkie avatar damieng avatar dependabot[bot] avatar driverpt avatar edusperoni avatar escardin avatar frederikprijck avatar heymp avatar joshcanhelp avatar krotscheck avatar laoujin avatar mattlewis92 avatar mischkl avatar nertzy avatar noopur-tiwari avatar noumaans avatar patricio-ezequiel-hondagneu-roig avatar patrickjs avatar ritave avatar robertrad avatar rostalevicek avatar royipressburger avatar rusmaxim avatar sabartius avatar sambego avatar theromis 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  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

angular2-jwt's Issues

headerPrefix setting

If I set headerPrefix = 'Bearer', the request would fail because the request header would look like
Authorization:BearereyJ....

It should put a space between the headerPrefix and token when building the header. Right now the workaround is to set headerPrefix = 'Bearer '.

return new AuthConfig({
headerName: 'Authorization',
headerPrefix: 'Bearer', ---- this would cause problem
tokenName: 'id_token',
tokenGetter: (() => localStorage.getItem('id_token')),
noJwtError: false
})

How to integrate with systemjs?

i took a look at your example but i'm still struggling to integrate with my sample app. i'm using ng2 beta0. am i doing this correctly? can you please help?

these are my errors:
TypeError: p is undefined
Error: Multiple anonymous System.register calls in module http://localhost:51939/scripts/angular2-jwt/angular2-jwt.js. If loading a bundle, ensure all the System.register calls are named.

this is my head section:

<script src="scripts/system.src.js"></script>
<script src="scripts/angular2-polyfills.js"></script>
<script src="scripts/Rx.js"></script>
<script src="scripts/angular2.dev.js"></script>
<script src="scripts/router.dev.js"></script>
<script src="scripts/http.dev.js"></script>

<script>
    System.config({
        packages: {
            app: {
                format: 'register',
                defaultExtension: 'js'
            },
            "angular2-jwt": {
                defaultExtension: "js"
            }
        },
        map: {
            "angular2-jwt": "scripts/angular2-jwt"
        }
    });
    System.import('app/boot')
          .then(null, console.error.bind(console));
</script>

Mocking AuthHttp

This is a awesome lib. Keep up the good work.

Just curious, is there some documentation for unit testing services using AuthHttp?

observable issue after upgrading to angular2 beta7

Hello,

after upgrading my angular2 project from beta2 to beta7 I have the following issue:
Type 'Observable<any>' is not assignable to type 'Observable<any>'. Property 'source' is protected but type 'Observable<T>' is not a class derived from 'Observable<T>'.
Reason is that this project depends on rxjs 5.0.0-beta.0, but angular moved to rxjs 5.0.0-beta.2, and the Observable changed.
PR follows...

Greetings, Marc

Errors trying to integrate angular2-jwt (auth0) into node.js/angular2 app using Systemjs

Hey,

So I've been tackling this for the past few days straight and still can't seem to make headway. I'm copying the angular2-jwt.js file from node_modules into the public/auth folder using gulp and then mapping it using Systemjs as follows:

map: { "angular2-jwt": "auth/angular2-jwt/angular2-jwt.js" }

The angular-jwt.js file is being found as there is no 404, however it's throwing up this error with angular2.js.

Any clues on where to go from here would be appreciated (I'm pretty new to node/angular development)

Stack Trace:
`EXCEPTION: The selector "app" did not match any elements
angular2.js:22823 EXCEPTION: The selector "app" did not match any elementsBrowserDomAdapter.logError @ angular2.js:22823BrowserDomAdapter.logGroup @ angular2.js:22834ExceptionHandler.call @ angular2.js:1163(anonymous function) @ angular2.js:12481NgZone._notifyOnError @ angular2.js:13405collection_1.StringMapWrapper.merge.onError @ angular2.js:13309run @ angular2-polyfills.js:141(anonymous function) @ angular2.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.js:13360run @ angular2-polyfills.js:138(anonymous function) @ angular2.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
angular2.js:22823 STACKTRACE:BrowserDomAdapter.logError @ angular2.js:22823ExceptionHandler.call @ angular2.js:1165(anonymous function) @ angular2.js:12481NgZone.notifyOnError @ angular2.js:13405collection_1.StringMapWrapper.merge.onError @ angular2.js:13309run @ angular2-polyfills.js:141(anonymous function) @ angular2.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.js:13360run @ angular2-polyfills.js:138(anonymous function) @ angular2.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
angular2.js:22823 Error: The selector "app" did not match any elements
at new BaseException (http://localhost:3000/dist/lib/angular2.js:7104:21)
at DomRenderer.selectRootElement (http://localhost:3000/dist/lib/angular2.js:13724:15)
at HostViewFactory.viewFactory_HostApp0 as viewFactory
at AppViewManager
.createRootHostView (http://localhost:3000/dist/lib/angular2.js:9226:34)
at http://localhost:3000/dist/lib/angular2.js:12246:46
at Zone.run (http://localhost:3000/dist/lib/angular2-polyfills.js:138:17)
at Zone.run (http://localhost:3000/dist/lib/angular2.js:13328:32)
at zoneBoundFn (http://localhost:3000/dist/lib/angular2-polyfills.js:111:19)
at lib$es6$promise$$internal$$tryCatch (http://localhost:3000/dist/lib/angular2-polyfills.js:1511:16)
at lib$es6$promise$$internal$$invokeCallback (http://localhost:3000/dist/lib/angular2-polyfills.js:1523:17)

-----async gap-----
Error
at getStacktraceWithUncaughtError (http://localhost:3000/dist/lib/angular2-polyfills.js:2195:26)
at Zone.fork (http://localhost:3000/dist/lib/angular2-polyfills.js:2253:40)
at Zone.bind (http://localhost:3000/dist/lib/angular2-polyfills.js:109:48)
at bindArguments (http://localhost:3000/dist/lib/angular2-polyfills.js:980:29)
at lib$es6$promise$promise$$Promise.obj.(anonymous function) as then
at DynamicComponentLoader
.loadAsRoot (http://localhost:3000/dist/lib/angular2.js:12245:49)
at di_1.provide.useFactory (http://localhost:3000/dist/lib/angular2.js:12343:39)
at Injector._instantiate (http://localhost:3000/dist/lib/angular2.js:11354:19)
at Injector._instantiateProvider (http://localhost:3000/dist/lib/angular2.js:11287:21)
at Injector._new (http://localhost:3000/dist/lib/angular2.js:11277:19)

-----async gap-----
Error
at _getStacktraceWithUncaughtError (http://localhost:3000/dist/lib/angular2-polyfills.js:2195:26)
at Zone.fork (http://localhost:3000/dist/lib/angular2-polyfills.js:2253:40)
at NgZone.createInnerZone (http://localhost:3000/dist/lib/angular2.js:13316:39)
at new NgZone (http://localhost:3000/dist/lib/angular2.js:13182:32)
at createNgZone (http://localhost:3000/dist/lib/angular2.js:12365:12)
at PlatformRef
.application (http://localhost:3000/dist/lib/angular2.js:12440:31)
at Object.bootstrap (http://localhost:3000/dist/lib/angular2.js:24543:64)
at execute (http://localhost:3000/dist/boot.js:113:23)
at ensureEvaluated (http://localhost:3000/dist/lib/system.src.js:2981:26)
at Object.execute (http://localhost:3000/dist/lib/system.src.js:3099:13)BrowserDomAdapter.logError @ angular2.js:22823ExceptionHandler.call @ angular2.js:1166(anonymous function) @ angular2.js:12481NgZone._notifyOnError @ angular2.js:13405collection_1.StringMapWrapper.merge.onError @ angular2.js:13309run @ angular2-polyfills.js:141(anonymous function) @ angular2.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.js:13360run @ angular2-polyfills.js:138(anonymous function) @ angular2.js:13328zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305`

'LoggedInRouterOutlet' don't work fine with [routerLink]

Hello, my company use Apache servers. I had to turn on routes with "#" with "HashLocationStrategy" so users can enter urls directly daughters.

...
provide(LocationStrategy, {useClass: HashLocationStrategy}),
...

The first mistake is that when you give the links, the "LoggedInRouterOutlet" does not detect that you're going to the "home" and can enter freely. I have resolved by inserting the following code in the home "constructor":

constructor(public router: Router, public http: Http, public authHttp: AuthHttp) {
    this.jwt = localStorage.getItem('jwt');    
    if (!this.jwt) {
      this.router.parent.navigateByUrl('/login');
    }
    this.decodedJwt = this.jwt && window.jwt_decode(this.jwt);
  }

Now, the problem is in the "signup" function of the "Login" controler, because "this.router.parent.navigateByUrl('/signup');" don't work and I do not know why. I changed the link in the template by:

<a [routerLink]="['Signup']">Click here to Signup</a>

But it does not work when you press the first time, from the second works. Any suggestions for that is detected you go to the home of a better way? THANKS and congratulations for your product

Refresh Token Support

Do you have any plans to build in support for refresh tokens?

Your equivalent Angular 1 lib has a Refresh Token Example but that's based on a different concept of interceptors which isn't available in v2.

I'm thinking it would probably be built into the _request method to refresh the token if it was expired or close to expiry - maybe a configurable function that the app can provide.

A neat feature would be for it to do a refresh in the background based on a configurable offset (so the token was refreshed as it got close to expiring prior to any API requests).

Just wondering if you already have plans for it and if not, if you'd have any objections to it being added ...

npm downloads wrong version

Hi all,

For some reason I wasn't getting the AUTH_PROVIDERS and after a quick research I realized that I had an old version. Strange because I never used angular2-jwt in the past. So after deleting it and reinstalling(npm install angular2-jwt) I saw that I was still getting the old version. Npm cache clean didn't help. Any ideas?
version

tokenNotExpired and AuthConfig

Hi,

I am using angular2-jwt for my first angular 2 app.
I find it quite easy to use, which is nice :)

I have a simple question, and it's about the tokenNotExpired function, as well as the AuthConfig.

Is it possible for the tokenNotExpired function to get the tokenName from the AuthConfig (as well as the getter function?) ?

Injected authconfig into my component did not make it available in the @CanActivate annotation.

I might as well just rename my token to the default id_token, but I think it would be nice to get the same config everywhere.

I have no idea if this is a simple task or not, as I am just starting with Angular 2 (without any Angular 1 background).

Anyway, thanks for this little plugin,

Cheers!

Error compiling ts to js

Using "angular2-jwt": "0.1.2"
tsc gives this error:
node_modules/angular2-jwt/src/angular2-jwt.ts(66,39): error TS7006: Parameter 'obs' implicitly has an 'any' type.

No provider for Http!

I am getting the following error:

EXCEPTION: No provider for Http! (Login -> AuthHttp -> Http)

main.ts

import {provide} from 'angular2/core';
import {bootstrap, ELEMENT_PROBE_PROVIDERS} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {HTTP_PROVIDERS, ConnectionBackend} from 'angular2/http';
import {App} from './app/app';
import {AuthHttp, JwtHelper, AuthConfig} from 'angular2-jwt';
import {AuthService} from './app/services/auth/authService';

document.addEventListener('DOMContentLoaded', function main() {
  bootstrap(App, [
    ('production' === process.env.ENV ? [] : ELEMENT_PROBE_PROVIDERS),
    HTTP_PROVIDERS,
    ROUTER_PROVIDERS,
    provide(LocationStrategy, { useClass: HashLocationStrategy }),
    provide(AuthConfig, { useFactory: () => {
      return new AuthConfig({
        headerName: 'Authorization',
        headerPrefix: 'Bearer ',
        tokenName: 'auth_token',
        noJwtError: true
      });
    }}),
    AuthHttp,
    AuthService,
    ConnectionBackend
  ])
  .catch(err => console.error(err));
});

login.ts

import {Component} from 'angular2/core';
import {
  FORM_DIRECTIVES,
  FormBuilder,
  ControlGroup,
  Validators,
  AbstractControl,
  Control
} from 'angular2/common';
import {Http, Headers} from 'angular2/http';
import {Router} from 'angular2/router';
import {ButtonRadio} from 'ng2-bootstrap/ng2-bootstrap';
import {AuthHttp, JwtHelper, AuthConfig} from 'angular2-jwt';
import {AuthService} from '../../services/auth/authService';
import {AlertService} from '../../services/alerts/alertsService';
import {User} from '../../datatypes/user/user';

@Component({
  selector: 'login',
  template: require('./login.html'),
  directives: [ ButtonRadio, FORM_DIRECTIVES ],
  providers: [Http, AuthService, AlertService]
})

export class Login {
  loginForm: ControlGroup;
  email: AbstractControl;
  password: AbstractControl;
  constructor(
    private http: Http,
    private authHttp: AuthHttp,
    private authService: AuthService,
    private alertService: AlertService,
    private fb: FormBuilder,
    private router: Router) {
      function emailValidator(control: Control): { [s: string]: boolean } {
        if (control.value.length > 0 && !control.value.match(/.+@.+\..+/i)) {
          return {invalidEmail: true};
        }
      }
      function passwordLengthValidator(control: Control): { [s: string]: boolean } {
        if (control.value !== '' && control.value.length < 6) {
          return {passwordLengthInvalid: true};
        }
      }
      this.loginForm = fb.group({
        'email': ['', Validators.compose([
          Validators.required, emailValidator])],
        'password': ['', Validators.compose([
          Validators.required, passwordLengthValidator])]
      });
      this.email = this.loginForm.controls['email'];
      this.password = this.loginForm.controls['password'];

      this.authService = authService;
      this.alertService = alertService;
  }
  login(user) {
    console.log('inside login.ts function');
    console.log(user);
    this.authService.login(user)
    .subscribe(
      res => {
        this.authService.saveJwt(res.auth_token);
      },
      err => {
        (<Control>this.loginForm.controls['password']).updateValue('');
        (<Control>this.loginForm.controls['password']).pristine = true;
        this.alertService.addAlert('There was an error loggin in.', 'danger');
      },
      () => {
        this.authService.token = localStorage.getItem('auth_token');
        this.router.navigate(['Home']);
      }
    );
  }
}

authService.ts

import {Http, Headers} from 'angular2/http';
import {Router} from 'angular2/router';
import {Injectable} from 'angular2/core';
import {AuthHttp, JwtHelper, AuthConfig} from 'angular2-jwt';

import {User} from '../../datatypes/user/user';

@Injectable()
export class AuthService {
  token: any;
  jwtHelper: JwtHelper = new JwtHelper();
  constructor(private http: Http, private router: Router, private authHttp: AuthHttp) { }
  saveJwt(jwt) {
    if (jwt) {
      localStorage.setItem('auth_token', jwt);
      this.token = localStorage.getItem('auth_token');
    }
  };
  deleteJwt() {
    localStorage.removeItem('auth_token');
    this.token = localStorage.getItem('auth_token');
  };
  isAuth() {
    var decoded: any;
    //decoded = this.jwtHelper(this.token);
    var date = new Date(0);
    date.setUTCSeconds(decoded.exp);
    if (date === null) {
      return false;
    }
    console.log(date);
    return (date.valueOf() > (new Date().valueOf()));
  }
  login(user) {
    console.log('inside authService.login');
    var header = new Headers();
    header.append('Content-Type', 'application/json');

    return this.authHttp.post('http://localhost:3000/login', JSON.stringify(user), {
      headers: header
    })
    .map(res => res.json());
    /*.subscribe(
      data => {
        alert('logging in');
        this.saveJwt(data.auth_token);
      },
      err => console.log(err),
      () => this.router.navigate(['Home'])
    );*/
  }
  logout() {
    /*var jwt = localStorage.getItem('auth_token');
    var authHeader = new Headers();
    if (jwt) {
      authHeader.append('Authorization', jwt);
    }*/
    var token = localStorage.getItem('auth_token');
    var header = new Headers();
    header.append('Content-Type', 'application/json');
    header.append('Authorization', token);
    console.log(token);

    return this.authHttp.delete('http://localhost:3000/logout', {
      headers: header
    })
    .map(res => res.json());
    /*.subscribe(
      data => this.deleteJwt(),
      err => console.log(err),
      () => this.router.navigate(['Login'])
    );*/
  }
  isLoggedIn() {
    //_jwt === localStorage.getItem('auth_token');
  }
}

Unclear how to do jwt without auth0 using angular2

I'm wondering how it would be possible to take out the lock login part and still use jwt.
Given that this seems an official angular2 package, I'm very curious how to generate the id_token.
It would be great if there would be resource displayed.

Cannot specifiy custom headers

It is not currently possible to use the full http api you are wrapping, as I cannot set portions of my request object.

Uncaught ReferenceError: require is not defined

in my cordova typescript project i used following to pull this package in
npm install angular2-jwt

then in the project's www/index.html i added
<script src="node_modules/angular2-jwt/angular2-jwt.js"></script>

and in the project's app.component.ts, which main.ts loads via "bootstrap(AppComponent);" i added
import {JwtHelper} from 'angular2-jwt';

now when i execute f5 debug/test using ripple emulator i get
Uncaught ReferenceError: require is not defined
angular2-jwt.js (10,14)

where looking at that the line 10, col 14 section of angular2-js.js i see the following line
var core_1 = require('angular2/core');

question - am i missing some step to enable a dependency package in order for this ng2 compatible package to be usable?

Usage with universal

Hi, can this module be used with angular2-universal-preview ? https://github.com/angular/universal/

I tried to set it up but it doesn't like the routing functions such as loggedIn()

I have a server and a client.js that bootstrap the same app.js with routes that use the loggedIn() but the server throws an error that it can't find loggedIn() under the context.

Error when doing authHttp.get with angular beta.1?

Hello,
I included auth0 in my angular beta.1 test project.
The login works quite well, but when I try to do an authenticated html request with
this.authHttp.get I get an error.

After debugging it seems to me that we are not giving the correct request parameters in the library.
In the documentations that I looked at, |request| needs first a url string and then a options object.

Line 97: request = this.http.request(req); here I have the error, the req object seems fine.

Would be great to know if you also have an error or not.

In the auth0 example project it seems to work, but they have different dependencies so maybe there were some breaking changes?

UPDATE:
I followed the debugging inside angulars http.request and it seems like they try to validate if the object is a proper request object:
else if (url instanceof static_request_1.Request) {
This fails, is it possible something changed and the request object needs to be constructed differently?

I checked the example project the same way and here the url object is validated as a proper request.
So it seem they changed something in beta.1?

Thanks.

Global Header

I need to send in all requests Content-type = application/json charset=utf-8.
Would be great if was possible to add global header configuration instead of set on each request

var myHeader = new Headers();
myHeader.append('Content-Type', 'application/json charset=utf-8');

this.authHttp.get('http://example.com/api/thing', { headers: myHeader} )

Thank you!

More relaxed angular2 dependency

The angular2 dependency is fixed at the moment. Could this be updated to be more relaxed with either ~ or ^ so that the library can better keep up to date with angular2 now they're in beta stages?

i.e.
"angular2": "^2.0.0-beta.0"

Post Install Error on CI about typings install command

We have integrated your library into our TeamCity CI server and we got always error about post install action:

[00:01:43]Step 2/7: NPM install (Node.js NPM) (5m:39s)
[00:01:44][Step 2/7] npm install (5m:38s)
[00:07:20][npm install] npm ERR! Windows_NT 6.2.9200
[00:07:20][npm install] npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
[00:07:20][npm install] npm ERR! node v4.2.6
[00:07:20][npm install] npm ERR! npm  v2.14.12
[00:07:20][npm install] npm ERR! code ELIFECYCLE
[00:07:20][npm install] npm ERR! [email protected] postinstall: `typings install`
[00:07:20][npm install] npm ERR! Exit status 1
[00:07:20][npm install] npm ERR! 
[00:07:20][npm install] npm ERR! Failed at the [email protected] postinstall script 'typings install'.
[00:07:20][npm install] npm ERR! This is most likely a problem with the angular2-jwt package,
[00:07:20][npm install] npm ERR! not with npm itself.
[00:07:20][npm install] npm ERR! Tell the author that this fails on your system:
[00:07:20][npm install] npm ERR!     typings install
[00:07:20][npm install] npm ERR! You can get their info via:
[00:07:20][npm install] npm ERR!     npm owner ls angular2-jwt
[00:07:20][npm install] npm ERR! There is likely additional logging output above.
[00:07:22][npm install] npm ERR! Please include the following file with any support request:
[00:07:22][npm install] npm ERR!     C:\TeamCity\buildAgent\work\41c7914645be8cdf\***\npm-debug.log
[00:07:22][Step 2/7] Step NPM install (Node.js NPM) failed

The main problem, i guess, is that "typings" is not installed globally on our system anyway i think it is better to exclude typings command, if a developer would like to use TypeScript has to know how to manage typings/d.ts and so on.....what do you think?
So Thanks.
Diego

tokenNotExpired don't use tokenName from AuthConfig

Hi guys, I'm using angular2-jwt and I realized that when I call tokenNotExpired without provide a tokenName he uses 'id_token' as you can look here:
var authToken:string = tokenName || 'id_token';

I think that angular2-jwt should use token name from AuthConfig instead a fixed value.

Error on Angular beta.9

Getting the following error in the _request() method:

First argument must be a url string or Request instance.

Unexpected token <

I am trying to use angular2-jwt. However I am getting the following error when trying to use it:

Uncaught SyntaxError: Unexpected token <
    Evaluating http://localhost:3000/angular2-jwt/angular2-jwt
    Error loading http://localhost:3000/app/main.js

I've followed the example, so my guess is that I am somehow failing to import it correctly.

It's included in my index.html <script src="node_modules/angular2-jwt/angular2-jwt.js"></script>

I've imported it to my app component import {AuthHttp, AuthConfig} from 'angular2-jwt';

And finally I have registered it in my providers array:

        provide(AuthHttp, {
            useFactory: (http) => {
                return new AuthHttp(new AuthConfig(), http);
            },
            deps: [Http]
        })
        AuthHttp,

What have I done wrong?

Support Silhouette (Play framework)

Hi,
I'm using Silhouette with JWT for authorization. In current implementation, they'll read a custom header for the token. The problem is they don't expect "Bearer" as the prefix. Currently, I cannot set header prefix to be empty (from the source code you will add Bearer if I pass in an empty string).

Is it a good idea to remove the default "Bearer"?

Error: JWT must have 3 parts

Hi!

I haver the following error:

error-angular2-jwt

Code of services (working before I was changed Http to AuthHttp) is:

login(email, password)
{
  let body = JSON.stringify({email: email, password: password});
  return this._http.post(this._protocol.API_URI_ACCOUNT_LOGIN, body, {headers: contentHeaders})
  .map(res => res.json())
  .catch(this._logAndPassOn);
}

Do you know if I have any error or maybe is a bug?

Thanks.

"Supplied parameters do not match any signature of call target"

I get an error: "TS2436: Supplied parameters do not match any signature of call target" on the return new AuthHttp(); line. ("angular2-jwt": "^0.1.7")

import {AuthHttp, AuthConfig} from 'angular2-jwt/angular2-jwt';
...
document.addEventListener('DOMContentLoaded', function main() {
  bootstrap(App, [
    ...ENV_PROVIDERS,
    ...HTTP_PROVIDERS,
    ...ROUTER_PROVIDERS,
    provide(LocationStrategy, { useClass: PathLocationStrategy }),
    provide(AuthHttp, { 
      useFactory: () => {
          return new AuthHttp()
        }
      }
    )
  ])
  .catch(err => console.error(err));
});

check if a token is valid

How can I check if a token is valid or not?
tokenNotExpired() only checks the expiry date of the valid token. What if the token itself is not properly formatted(i.e asd.asd.asd)?

options HTTP request method support

Hello, it could be great to add support for the OPTIONS http verb in AuthHttp.

This operation could be useful when using self-describing RESTful APIs.

I have made this pull request : #57 in order to fix this issue.

Return observable error if JWT is invalid

For the next release, we'll return an observable.error when a JWT is invalid instead of throwing an error.

return new Observable((obs:any) => {
  obs.error(new Error('Invalid JWT'));
});

can not install

i got these error when run "npm install angular2-jwt"
npm WARN install Refusing to install angular2-jwt as a dependency of itself

Importing this library modifies the typescript relative file paths

It took me 6 hours to realize, that adding this line

"import { AuthHttp } from "angular2-jwt/angular2-jwt";" effectively changed my build system, by somehow modifying the typescript compilation scope to change all files relative location.

I'm a little sick of debugging the typescript compiler and gulp vinyl streams, so this ticket should serve as a warning to others, that have the same problem.

Authorization header and global headers missing in request

"angular2": "2.0.0-beta.13",
"angular2-jwt": "^0.1.12",
"es6-promise": "3.0.2",
"es6-shim": "^0.35.0",
"ionic-angular": "2.0.0-beta.4",
"ionic-native": "^1.1.0",
"ionicons": "3.0.0-alpha.3",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.2",
"zone.js": "0.6.6"

  config: {}, // http://ionicframework.com/docs/v2/api/config/Config/,
  providers:[HTTP_PROVIDERS, provide(AuthHttp, {
    useFactory: (http) => {
      return new AuthHttp(new AuthConfig({
        headerName: "Authorization",
        headerPrefix: "Bearer",
        tokenName: "token",
        tokenGetter: (() => localStorage.getItem('token')),
        globalHeaders: [{'Content-Type':'application/json'}],
        noJwtError: false,
        noTokenScheme: false
      }), http);
    },
    deps: [Http]
  })]
})
this.authHttp.get('http://api-137653.nitrousapp.com:3000/api/profile')
            .subscribe(
            data => console.log(data),
            err => console.log(err),
            () => console.log('Request Complete')
            );

FInal request
selection_001

Sending multipart/form-data

Hi, I'm trying to figure out how can I send a file along with other form data. People usually encode the req body with multipart/form-data.
What would my post-body would look like? Previously I used a stringified json string.

Newbie Import Issue

I added "angular2-jwt": "0.1.9" to the dependencies section of my package.json file.
Then I ran npm install
I now have the angular2-jwt library in my node_modules folder.

I import the library into my app.component.ts with this line: import {AuthHttp, AuthConfig} from 'angular2-jwt'; which seems to work correctly. The issue comes when I try to actually use the library.

This is my app.component.ts constructor

constructor(public authHttp: AuthHttp) { }

Once I do this my application stops working and I get the following error in my command window:
16.04.06 12:51:41 404 GET /angular2-jwt

This is the error I get in my F12 tools window:
Failed to load resource: the server responded with a status of 404 (Not Found) angular2-polyfills.js:332
Error: Error: XHR error (404 Not Found) loading http://localhost:3000/angular2-jwt(…)
ZoneDelegate.invoke @ angular2-polyfills.js:332

It appears that the system is attempting to find a file called angular2-jwt in my root directory instead of dynamically loading it from the node_modules folder.

I have had this sort of issue before and have gotten it to go away but I can't figure out how.

rxjs version issue

I get an error when installing my dependencies because I'm using beta4 of rxjs, but angular2-jwt requires beta2. I'm a little stuck because I currently need beta4. Is there anything I can do or I should just wait for an update?

error is: npm WARN [email protected] requires a peer of [email protected] but none was installed.

Strange thing is that beta4 is installed, but it's not picked up...

First argument must be a url string or Request instance.

Receving this error from an AuthHttp instance.

Code:
constructor(private menu: MenuController, private nav: NavController, private authHttp: AuthHttp){
this.menu = menu;
this.authHttp.get('api/cars.json')
.map(res => res.json() )
.subscribe( cars => {
this.cars = cars;
});
}

browser_adapter.ts:73 TypeError: First argument must be a url string or Request instance.
at Object.makeTypeError (exceptions.ts:45)
at Http.request (http.ts:112)
at AuthHttp._request (angular2-jwt.js:80)
at AuthHttp.requestHelper (angular2-jwt.js:89)
at AuthHttp.get (angular2-jwt.js:92)
at new PadList (pad-list.ts:72)
at reflection_capabilities.ts:31
at Injector._instantiate (injector.ts:825)
at Injector._instantiateProvider (injector.ts:770)
at Injector._new (injector.ts:759)

"dependencies": {
"angular2": "^2.0.0-beta.7",
"angular2-jwt": "^0.1.9",
"es6-promise": "3.0.2",
"es6-shim": "0.33.13",
"ionic-angular": "2.0.0-beta.3",
"ionic-native": "^1.1.0",
"ionicons": "3.0.0-alpha.3",
"reflect-metadata": "0.1.2",
"rxjs": "^5.0.0-beta.2",
"zone.js": "^0.5.15"
},

ionic 2 provider support

I tried using this great library out of the box with ionic 2 today.

Ionic 2 doesn't bootstrap, but instead uses a providers input on the main app component.

It looks like this:

providers: [
AuthHttp,
AuthConfig
]

I cannot find a way to set a configuration like you can with angular 1's factory way.

The default config (or not setting one) doesn't work in this case as it errors out.

I was able to get it to work though setting this in the ctor of AuthConfig:

this.config = {};

After that it worked although when it didn't find a token, it doesn't error out gracefully at this point.

However, the three helper methods worked out just great, as long as a token exists.

Great work!

Angular2 beta 17 requires rxjs beta 6 which breaks angular2-jwt

With: "angular2-jwt": "^0.1.12"

After installing "angular2": "2.0.0-beta.17" and the required "rxjs": "5.0.0-beta.6" the following errors occure:

TSError: ⨯ Unable to compile TypeScript
node_modules/angular2-jwt/angular2-jwt.ts (99,9): Type 'Observable<Response>' is not assignable to type 'Observable<Response>'.
  Property 'source' is protected but type 'Observable<T>' is not a class derived from 'Observable<T>'. (2322)
node_modules/angular2-jwt/angular2-jwt.ts (114,7): Type 'Observable<Response>' is not assignable to type 'Observable<Response>'. (2322)
node_modules/angular2-jwt/angular2-jwt.ts (128,7): Type 'Observable<Response>' is not assignable to type 'Observable<Response>'. (2322)

Support Base URL

Hi, I think it would be nice to support baseURL. We can add 1 more field to AuthConfig and add that base URL into the requestHelper method.

error TS2322: Type 'Response' is not assignable to type 'string'.

import {AuthHttp, AuthConfig} from 'angular2-jwt';

...

class App {

  thing: string;

  constructor(public authHttp: AuthHttp) {}

  getThing() {
    this.authHttp.get('http://example.com/api/thing')
      .subscribe(
        data => this.thing = data, // here , data is Response Type,how can set for this.thing??
        err => console.log(error),
        () => console.log('Request Complete')
      );
  }
}

bootstrap(App, [
  HTTP_PROVIDERS,
  provide(AuthHttp, {
    useFactory: (http) => {
      return new AuthHttp(new AuthConfig(), http);
    },
    deps: [Http]
  }),
  AuthHttp
])

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.