Security access in NativeScript Angular app

Issue

I’m starting to learn NativeScript Angular (I’m used to develop webapp/websites using Angular) and I’m still kind of confused on how to create some restricted access on the NativeScript app, or to restrict a specific route and/or sets of routes.

For example, in Angular I use uiRouter to define some data, like this:

data: {
    requireLogin: true
}

In each page transition I check if there is a valid token to garantee access to that user. On the NativeScript I was thinking about it and could do the same thing, I just don’t know, since I’m very new to NativeScript and I don’t know if this would go against any best practices, or common security scenarios.

For example, I’ll be setting the token on the Application Settings after the login, something like this:

submit() {
    // process the login here
    if ( success ) {
        setString(AppSettings.authToken, authToken );
    }
}

And then I would set the routes to have a parent route with a parent component where I will check for this token, eg:

export class ParentComponent implements OnInit {
    constructor() {}

    ngOnInit() {
        if ( !getString(AppSettings.authToken)) {
            return this.router.navigate(["/login"]);
        }
    }
}

This way I would check if the user has a valid session when accessing the app on a restricted area.

However, for example, in a normal Angular Application I also make use of interceptor, to check in every http request if the authToken is still valid.

How am I supposed to do in this case?

I tried to find any material on NativeScript Angular security but didn’t found any. is there any place where I can read more about this?

What should I have in mind when dealing with this type of scenario?

Solution

You can use the Angular’s route guards

Basic example for canActivate route guard in NativeScript

class AuthGuard implements CanActivate {
    constructor(
        private loginService: LoginService,
        private nav: RouterExtensions) {
    }

    canActivate() {
        if (this.loginService.isLogged) {
            console.log("AuthGuard: authenticated");
            return true;
        } else {
            console.log("AuthGuard: redirecting to login");
            this.nav.navigate(["/login"]);
            return false;
        }
    }
}

Based on this test application

The same deal in a real demo application. Here is the actual usage of this guard in the Sample-Groceries app.

Answered By – Nick Iliev

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.