Reputation: 740
I have an angular 2 app with JWT authentication (Auth0) that after user login stores the profile and token id in the localStorage, the profile contains a "role" attribute to check if the user can access an especific page. Everything works like a charm but if the user change the role property in the localStorage to "admin" for example and reload the app he can access pages that he is not authorized. How can I handle that?
auth.service.ts:
declare var Auth0Lock: any;
@Injectable()
export Class AuthService {
lock = new Auth0Lock(ID, domain);
user: Object;
constructor() {
this.user = JSON.parse(localStorage.getItem('profile'));
}
public login() {
// Auth0 method
this.lock.show({}, (err: string, profile: Object, token: string) => {
if (err) { console.log(err); return; }
localStorage.setItem('profile', JSON.stringify(profile));
localStorage.setItem('id_token', token);
});
}
public logout() {
localStorage.removeItem('profile');
localStorage.removeItem('id_token');
}
public loggedIn() {
return tokenNotExpired();
}
public isAdmin() {
if (this.user['role'] == 'admin') {
return true;
} else {
return false;
}
}
}
app.component.ts:
// imports, etc
export Class AppComponent {
constructor(private auth: AuthService) {}
}
app.component.html:
<nav>
<ul>
<li><a [routerLink]="['Customers']" *ngIf="auth.loggedIn()">Customers</a></li>
<li><a [routerLink]="['Admin']" *ngIf="auth.loggedIn() && auth.isAdmin()">Admin</a></li>
</ul>
</nav>
Any ideas to handle that would be appreciated
Upvotes: 0
Views: 1617
Reputation: 635
In my opinion, it's impossible to create fully secured pages/forms, when you have JavaScript front-end framework. I mean, there is always possibility to open any form, when all application is downloaded to and constructed at client side.
For me, it's important to secure back-end api, and leave "hacking" opportunities to junior developers.
If you have such requirements, try to use server side generated framework: php, asp.net mvc, jsp & etc.
UPDATE
As it came up, Angular2 has directive @CanActivate, which gives more accurate way to cancel navigaition. BUT server side authorization is CRITICAL in javascript front-end based applications.
This will help how to deal with JWT in express back-end: express-jwt
Upvotes: 2