-
Notifications
You must be signed in to change notification settings - Fork 15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Problems getting this working #1
Comments
Do you has installed peer dependencies? Check if you are using an JwtHttp object to do your requests. import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { JwtHttp } from 'angular2-jwt-refresh';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { AppConfig } from '../AppConfig';
@Injectable()
export class DataService {
private baseUrl: string = AppConfig.baseUrl + '/data';
constructor(private jwtHttp: JwtHttp) { }
getData(id: number): Observable<any> {
const url = this.baseUrl + '/' + id;
return this.jwtHttp
.get(url)
.map((res: Response) => {
return res.json();
});
}
saveData(data: any): Observable<string> {
const url = this.baseUrl + '/' (data['id'] ? data['id'] : '');
return this.jwtHttp
.post(url, data)
.map((res: Response) => {
return res.json();
});
}
} |
@shopro can you check if your token has For the token {
"exp": 1487677975
} If you don't provide |
The token is like this: I am not sure what you meant by using JwtHttp. I implemented it like this. I am new to Angular2 so I don't know if this is correct or not. The initial token is retrieved using AuthHttp from Angular2-jwt.
|
@shopro how do you do http requests? |
For the token part I'm using the angular2-jwt library.
|
@shopro You can replace AuthHttp to JwtHttp. JwtHttp extends AuthHttp, so JwtHttp has same utility of AuthHttp and adds refresh token funcionability. You don't need configure angular2-jwt anymore too, only angular2-jwt-refresh. |
Thanks for the info, I think it's simply my lag of experience why I can't get this working. Here is my exact setup after I tried to implement based on your tips. credentials variable is being provided by the login form. Maybe my problem is that once logged in it doesn't seem to run the refresh part? auth.service.ts
app.module.ts
|
@shopro after login you only set id_token, you forget to set refresh_token. I'm developing a auth.service for Ionic2 app: import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Storage } from '@ionic/storage';
import { JwtHttp } from 'angular2-jwt-refresh';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { AppConfig } from '../../app/app.config';
@Injectable()
export class AuthService {
private baseUrl = AppConfig.url;
static storage: Storage = new Storage();
constructor(public jwtHttp: JwtHttp,
public http: Http) { }
static tokenSetter(accessToken, refreshToken): Promise<void> {
return new Promise<void>((resolve, reject) => {
let idTokenFinish = false;
let refreshFinish = false;
AuthService.storage
.set('accessToken', accessToken)
.then(() => {
idTokenFinish = true;
if (refreshFinish) {
resolve();
}
})
.catch(reject);
AuthService.storage
.set('refreshToken', refreshToken)
.then(() => {
refreshFinish = true;
if (idTokenFinish) {
resolve();
}
})
.catch(reject);
});
}
login(user: any) {
return this.http
.post(this.baseUrl, user, AppConfig.requestOptions)
.map((res: Response) => {
let tokens: any = res.json();
if (!tokens.accessToken || !tokens.refreshToken) {
return null;
}
return tokens;
})
.concatMap(tokens => {
if (!tokens) {
return Observable.throw('Não foi possível realizar o login!');
}
return Observable.fromPromise(AuthService.tokenSetter(tokens.accessToken, tokens.refreshToken));
})
.catch((res: string | Response) => {
let message = 'Erro desconhecido, favor tentar novamente.';
if (res instanceof Response) {
res = res.json();
} else {
message = res;
}
if (res === 'NOT_FOUND') {
message = 'Email e/ou senha inválido(s)!';
}
return Observable.throw(message);
});
}
logout() {
return this.jwtHttp
.post(this.baseUrl, { action: 'logout' }, AppConfig.requestOptions)
.mergeMap(() => {
return Observable.fromPromise(AuthService.storage.clear());
});
}
loggedIn() {
return Observable.fromPromise(AuthService.storage.get('id_token'))
}
register(user) {
return this.http
.post(this.baseUrl, user, AppConfig.requestOptions)
.map(res => res.json())
.catch((res: Response) => {
let message = null;
if (res.json() === 'DUPLICATE') {
message = 'Email já cadastrado!';
}
return Observable.throw(message || 'Erro desconhecido, favor tentar novamente.');
});
}
} |
Thank you for the example, I however am still able to figure out how exactly to get it refreshed before it expires. I was able to make it so that both the 'id_token' and 'refresh_token' are being created on login but neither is being refreshed. Where and how do I "run" it so it refreshes? |
Yes, I'm using jwthttp for the login http request, this is the only http request I currently have. I'm currently only using http for authentication. |
So, the token only will update before a new request. angular2-jwt-refresh uses a strategy like request interceptors in AngularJS |
@shopro One more thing! For requests that's doesn't have a token in headers you can make this with Http. So for login, you don't need of angula2-jwt-refresh, use this only for requests after authenticated |
Posted in new thread |
Hi @leonardobazico , First of all thanks for sharing this great plugin with the community, I am developing an Ionic app but I am having a hard time with the localstorage, this is my use case: I have the setup suggested on the README, and on the other hand I have a provider (service) in which I am setting my tokens upon login, something such as: localStorage.setItem('token',token) But, the problem is, the first time jwt refresh is triggered my payload goes null, this is my payload: {'expiredToken' : localstorage.getItem('token'), 'rToken' : localstorage.getItem('refresh_token')} And the most weird, the next time I do the login process the sent over the previous values for token and refresh_token, would you please let me know what the heck is local storage doing? XD Thanks mam |
Hi @cantwait, @leonardobazico, I have a big issue regarding refresh call, it looks like the calls are correctly made, but for some reason after 1-2 calls my call to the refresh token path from server I have a canceled request and after that my app goes down. Here are my setup: export function getJwtHttp(http: Http, options: RequestOptions) {
let jwtOptions = {
endPoint: 'http://*/refresh',
payload: { type: 'refresh' },
beforeSeconds: 60 * 3,
tokenName: 'refresh_token',
refreshTokenGetter: (() => localStorage.getItem('refresh_token')),
tokenSetter: ((res: Response): boolean | Promise<void> => {
res = res.json();
if (!res['access_token'] || !res['refresh_token']) {
localStorage.removeItem('token');
localStorage.removeItem('refresh_token');
return false;
}
localStorage.setItem('token', res['access_token']);
localStorage.setItem('refresh_token', res['refresh_token']);
return true;
})
}; Do you have any idea why this happens? |
I have based on the example configuration tried to implement this to my project but it doesn't seem to be working. No matter what the
"beforeSeconds"
is set it doesn't fire at all.What is the proper way to have this refresh the token? The API is running Django REST framework and the command to refresh token is the following and the token expiry time is 300seconds.
curl -X POST -H "Content-Type: application/json" -d '{"token":"<EXISTING_TOKEN>"}' http://localhost:8000/api-token-refresh/
Thank you in advance.
The text was updated successfully, but these errors were encountered: