#ionic 4 authentication with authguard tutorial
Explore tagged Tumblr posts
i4technolab · 3 years ago
Link
Tumblr media
Here are the steps to create an Ionic application using Authguard, it is very common and acquired by most of the real world and many Ionic Mobile Application Development Companies
Open visual studio code and then open terminal in it.
Write command like “ionic start Demo —tabs”
Open the recently made application in visual studio code.
Type command like “ionic serve”. So it will run our application into our system’s default browser.
If you want to run out application in simulators, then there will be command like “ionic cordova run ios”.
To create login page there will be command like “ionic g page login”.
So the routing of login will be created at “app-routing.module.ts” file.
Now we want to restrict our user to access our main tab bar pages without authorization token. For that, we will create new module related to the core module with the command like “ionic g m core”.
We have to create Authguard via this command like “ionic g guard core/auth”. It will generate the guard in core folder.
Then create an activate method that will be used to make a route for tabs or login as per the authorization token which we have obtained at the time of login.
Now install the storage plugin for ionic 4, that will be used to store the token.
Import our ionic storage module in “app.module.ts” file.
Inject storage from Ionic storage module in auth guard file which is used for validation of authorization token.
We will do same business logic which can activate method that if we got the token then we have to navigate to our tabs screens otherwise move the user to login screens.
Now use same activate method in “app-routing.module.ts” file to prevent user to navigate to tabs screen with the guard file with the code like “canActivate: [AuthGuard]”.
Create some login page to add email and password things for the user with the reactive forms
So for that we have to import reactive forms module in “login.module.ts”
Do some validation for email and password as in-built validation provided in angular reactive forms?
Do some business logic like if our form is valid then store our authorization token into local storage and navigate to the tabs screen.
If we want to make some custom service that will handle our toast messages, then create toast service in our core folder with the command like “ionic g s core/toast”
Now import toast controller into toast service file and add method to present our dynamic toast messages.
Now we want to use toast service in the login screen so we have to import our toast service in “login.module.ts” file in “providers” array.
If you want to change any theme color of login page then we can easily change from “variables.scss” file.
Now all things are set and we have to run our application with command as described in step 4 or 5.
Now if we want to add Android platform then just write command like “ionic cordova platform add android”
After successfully adding platform, just run the command like “ionic cordova run android --device”. So it will run our app into android device
Now first it will display a login screen and we have to login with our credentials and if our form is valid then app will redirect to tabs screen.At last router will redirect to login page.
At last router will redirect to login page.
0 notes
mbaljeetsingh · 5 years ago
Text
Building an Authentication System with Ionic 4 and NestJS
Whether you celebrate Christmas or not, today is your happy day as I’ve prepared this special for all Devdactic followers!
Since I wanted to give back something to all the loyal followers of this blog, I created a little gift on one of the basics that you’ll hopefully enjoy!
Todays post is not really a tutorial, but a description of the code template that contains both a NestJS backend and also an Ionic app. As a result, once you run both parts you will have a full working authentication template ready for your next app!
You can get the whole gift package by entering your email in the box below.
Let’s talk about how and why it works, and what you need to set up upfront.
Prerequisite
It’s a good idea for both parts of the template to install Ionic and the Nest CLI locally to later build out the projects like this:
npm i -g @nestjs/cli npm i -g ionic
Of course you could also simply install the dependencies inside the project, but having both of them globally is anyway a good idea.
Also, the backend needs a MongoDB for holding the users. Therefore, install MongoDB on your local machine and while you are at it, I recommend to get a good GUI tool for managing your database like Studio 3T.
The Nest Backend
Before you run the backend you need to set a few values, and for this you have to rename the dummy.env file to .env which is the environment used for the application.
In there you can specify the port, the URI to the MongoDB (which should work like it is, the database will automatically be created) and finally a secret for the JWT authentication.
You need to make sure to have your MongoDB up and running now, and then you can go ahead and install all dependencies and run the backend like this:
cd ./api npm install nest start --watch
You should see some logging about the routes being set up, and if everything works your fresh API is now running at port 5000!
The routes of the API are also included in the HolidayGift.postman_collection which you can simply import to Postman to now test your API.
The routes are:
The API contains everything to register users, to login, get user data and delete accounts. Basically all CRUD operations for the user domain plus a login functionality.
In terms of code, you can find all the routes inside the src/users/users.controller.ts:
import { UserDto } from './dto/user.dto'; import { UsersService } from './users.service'; import { Controller, Get, Res, HttpStatus, Post, Body, Put, NotFoundException, Delete, Param, UseGuards } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Controller('users') export class UsersController { constructor(private userService: UsersService) {} @Post() async addUser(@Res() res, @Body() createUserDto: UserDto) { try { const user = await this.userService.addUser(createUserDto); return res.status(HttpStatus.OK).json({ msg: 'User has been created successfully', user }); } catch (e) { return res.status(HttpStatus.CONFLICT).json({ msg: 'User already exists' }); } } @UseGuards(AuthGuard()) @Get(':userID') async getUser(@Res() res, @Param('userID') userID) { const user = await this.userService.getUser(userID); if (!user) throw new NotFoundException('User does not exist!'); return res.status(HttpStatus.OK).json(user); } @UseGuards(AuthGuard()) @Put(':userID') async updateUser( @Res() res, @Param('userID') userID, @Body() createUserDto: UserDto, ) { const user = await this.userService.updateUser(userID, createUserDto); if (!user) throw new NotFoundException('User does not exist!'); return res.status(HttpStatus.OK).json({ msg: 'User has been successfully updated', user, }); } @UseGuards(AuthGuard()) @Delete(':userID') async deleteUser(@Res() res, @Param('userID') userID) { const user = await this.userService.deleteUser(userID); if (!user) throw new NotFoundException('User does not exist'); return res.status(HttpStatus.OK).json({ msg: 'User has been deleted', user, }); } @UseGuards(AuthGuard()) @Get() async getAllUser(@Res() res) { const users = await this.userService.getAllUser(); return res.status(HttpStatus.OK).json(users); } }
As you can see, all routes are also protected with a guard, and we are using JWT authentication in this API.
The logic for authentication can also be seen inside the src/authauth/users.service.ts:
import { Injectable } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { LoginUserDto } from '../users/dto/login-user.dto'; import { UsersService } from '../users/users.service'; import { JwtPayload } from './interfaces/jwt-payload.interface'; @Injectable() export class AuthService { constructor(private usersService: UsersService, private jwtService: JwtService){ } async validateUserByPassword(loginAttempt: LoginUserDto): Promise<any> { let userToAttempt: any = await this.usersService.findOneByEmail(loginAttempt.email); return new Promise((resolve) => { if (!userToAttempt) { resolve({success: false, msg: 'User not found'}); } userToAttempt.checkPassword(loginAttempt.password, (err, isMatch) => { if(err) resolve({success: false, msg: 'Unexpected error. Please try again later.'}); if(isMatch){ resolve({success: true, data: this.createJwtPayload(userToAttempt)}); } else { resolve({success: false, msg: 'Wrong password'}) } }); }); } createJwtPayload(user){ let data: JwtPayload = { id: user._id, email: user.email }; let jwt = this.jwtService.sign(data); return { exp: 36000, token: jwt } } async validateUser(payload: JwtPayload): Promise<any> { return await this.usersService.getUser(payload.id); } }
So you can register without a JWT of course, but all other routes are protected and you need to add the Authorization filed to your header with a value of “Bearer yourJWT”.
The Ionic App
There’s not much to say about the Ionic app, simply install the dependencies like always and then run it:
cd ./app npm install ionic serve
Inside your src/environments/environment.ts you can configure which backend will be used, and by default it will use my Heroku deployment – you should change this soon to your own local backend!
The logic of the app includes a login and register page, and a protected inside area that only users can enter because it’s protected by the auth-guard. Additionally there is another guard that is applied to all pages that are not protected in order to automatically log in users if they were authenticated before!
The code is a pretty simple check, and because it’s a guard you won’t see a page until we really receive the authentication state from the storage. You can find it inside the src/guards/auto-login.guard.ts:
import { Injectable } from '@angular/core'; import { CanActivate, Router } from '@angular/router'; import { Observable } from 'rxjs'; import { ApiService } from '../services/api.service'; import { take, map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AutoLoginGuard implements CanActivate { constructor(private api: ApiService, private router: Router) { } canActivate(): Observable<boolean> { return this.api.user.pipe( take(1), map(user => { if (!user) { return true; } else { this.router.navigateByUrl('/app'); return false; } }) ) } }
Besides that, all API interaction takes place inside the src/services/api.service.ts including the management of the JWT, for which we use once again the @auth0/angular-jwt package:
import { environment } from './../../environments/environment'; import { Platform } from '@ionic/angular'; import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; import { BehaviorSubject, Observable, from } from 'rxjs'; import { take, map, switchMap } from 'rxjs/operators'; import { JwtHelperService } from "@auth0/angular-jwt"; import { HttpClient } from '@angular/common/http'; import { Router } from '@angular/router'; const helper = new JwtHelperService(); export const TOKEN_KEY = 'jwt-token'; export interface User { first_name: string; last_name: string; email: string; avatar: string; bio: string; createdAt: string; _id: string; expanded?: boolean; } @Injectable({ providedIn: 'root' }) export class ApiService { public user: Observable<any>; private userData = new BehaviorSubject(null); constructor(private storage: Storage, private http: HttpClient, private plt: Platform, private router: Router) { this.loadStoredToken(); } loadStoredToken() { let platformObs = from(this.plt.ready()); this.user = platformObs.pipe( switchMap(() => { return from(this.storage.get(TOKEN_KEY)); }), map(token => { if (token) { let decoded = helper.decodeToken(token); this.userData.next(decoded); return true; } else { return null; } }) ); } login(credentials: {email: string, password: string }) { return this.http.post(`${environment.apiUrl}/auth`, credentials).pipe( take(1), map(res => { // Extract the JWT return res['token']; }), switchMap(token => { let decoded = helper.decodeToken(token); this.userData.next(decoded); let storageObs = from(this.storage.set(TOKEN_KEY, token)); return storageObs; }) ); } register(credentials: {email: string, password: string }) { return this.http.post(`${environment.apiUrl}/users`, credentials).pipe( take(1), switchMap(res => { console.log('result: ', res); return this.login(credentials); }) ); } getUserToken() { return this.userData.getValue(); } getUserData() { const id = this.getUserToken()['id']; return this.http.get<User>(`${environment.apiUrl}/users/${id}`).pipe( take(1) ); } getAllUsers(): Observable<User[]> { return this.http.get<User[]>(`${environment.apiUrl}/users`).pipe( take(1) ); } updateUser(id, data) { return this.http.put(`${environment.apiUrl}/users/${id}`, data).pipe( take(1) ); } removeUser(id) { return this.http.delete(`${environment.apiUrl}/users/${id}`).pipe( take(1) ); } logout() { this.storage.remove(TOKEN_KEY).then(() => { this.router.navigateByUrl('/'); this.userData.next(null); }); } }
As a final word: The JWT package needs to whitelist domains for which the JWT will be injected into HTTP calls. If you follow the next step and deploy your API somewhere, you need to make sure that you add your new backend URL inside the src/app/app.module.ts:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouteReuseStrategy } from '@angular/router'; import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { IonicStorageModule, Storage } from '@ionic/storage'; import { HttpClientModule } from '@angular/common/http'; import { TOKEN_KEY } from './services/api.service'; import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt'; export function jwtOptionsFactory(storage) { return { tokenGetter: () => { return storage.get(TOKEN_KEY); }, whitelistedDomains: ['localhost:5000', 'holidaygift.herokuapp.com'] // Add your Heroku URL in here! } } @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, IonicStorageModule.forRoot(), HttpClientModule, JwtModule.forRoot({ jwtOptionsProvider: { provide: JWT_OPTIONS, useFactory: jwtOptionsFactory, deps: [Storage] } })], providers: [ StatusBar, SplashScreen, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule {}
Now let’s see how you can deploy the backend.
Deployment
For the dummy deployment I used Heroku, and you can use it as well to quickly get your API up and running not only on your local machine.
You can basically follow the official Heroku guide to create a new app and push your code to it.
In addition you need to perform 2 further steps.
Add the mLab integration
The API needs a database, and you can easily add a cloud hosted MongoDB to your Heroku app inside the resources tab like this:
Environment Variables
The database will autoamtically write a variable like we did with our local environment file, but you also need to add the value for the JWT_SECRET which you can do inside the settings tab:
Over to You
Now you can use the Heroku URL and use it in your Ionic app, and you have a full blown authentication app in your hands.
Hopefully this is the starting point for your next project, and perhaps you already had some plans for the holiday season?
Definitely let me know if you enjoy the template by tweeting at me or tag me on Instagram!
I would love to see the template in action. You can also find a short video explanation of the authentication template in the video below.
Thanks for all your support and see you again next year, Simon
youtube
The post Building an Authentication System with Ionic 4 and NestJS appeared first on Devdactic.
via Devdactic https://ift.tt/2sk2PUH
0 notes
i4technolab · 5 years ago
Link
Ionic 4 is using Angular Routing, so it becomes very simple to add authentication in an Ionic application using Auth Guards. The Ionic Auth Guards are the Ionic version of the Angular Navigation Guards. Here in this blog we will explain what is Ionic guard and How to use Authguard in Ionic 4.
0 notes
mbaljeetsingh · 7 years ago
Text
Building a Basic Ionic 4 Login Flow with Angular Router
It’s time for Ionic v4 content, and what fit better than the all-time classic login flow example? With Ionic 4 it becomes a lot easier to protect our apps the real Angular way using the Angular Router.
Inside this (quite long) tutorial we will build a dummy authentication flow logic for an Ionic 4 app using Angular. We are not going to use a real backend or users, but you can easily plug in the calls to your API in the right places and use this logic as a blueprint for your authentication.
At the time writing this I’m using the v4 Beta so things might change a bit over time. If you encounter problems, just leave a comment below this tutorial.
We will use the CLI, Angular Router, Guards, Services.. Let’s do this!
Creating the Ionic Basic App
We start with a blank Ionic app and generate a few pages and services at the appropriate places inside our app. Also, I’m using the Angular CLI to generate an additional module inside the members folder (which should be created after running the commands).
Perhaps this will also work with the Ionic CLI soon, but as the Angular CLI is closely integrated in Ionic 4 projects there’s no problem in using it so go ahead and bootstrap your project like this:
ionic start devdacticLogin blank --type=angular
cd devdacticLogin
npm install --save @ionic/storage
ionic g page public/login
ionic g page public/register
ionic g page members/dashboard
ionic g service services/authentication
ionic g service services/authGuard
ng generate module members/member-routing --flat
The --flat simple means to create no additional folder for the file!
You can now also go ahead and remove the app/home folder and we will also remove the other references to the HomePage later.
We also want to use the Ionic Storage inside our app which you would later use to store your JWT so we need to add it to our app/app.module.ts like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
 import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
 import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { IonicStorageModule } from '@ionic/storage';
 @NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    IonicStorageModule.forRoot()
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
That’s the basic setup so far, now we can focus on adding some security.
Adding Authentication Provider and Guard
Like always it’s a good idea to have the authentication logic in one place, and here it is our AuthenticationService. This service will handle the login/logout and in our case perform just dummy operations.
Normally you would send the credentials to your server and then get something like a token back. In our case we skip that part and directly store a token inside the Ionic Storage. Then we use our BehaviorSubject to tell everyone that the user is now authenticated.
Other pages can subscribe to this authenticationState or check if the user is authenticated using the current value of the Subject.
Although we don’t have any real Server attached, the logic and flow is nearly the same so you could use this as a base for your own authentication class.
Now go ahead and change the app/services/authentication.service.ts to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { Platform } from '@ionic/angular';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';
import { BehaviorSubject } from 'rxjs';
 const TOKEN_KEY = 'auth-token';
 @Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
   authenticationState = new BehaviorSubject(false);
   constructor(private storage: Storage, private plt: Platform) {
    this.plt.ready().then(() => {
      this.checkToken();
    });
  }
   checkToken() {
    this.storage.get(TOKEN_KEY).then(res => {
      if (res) {
        this.authenticationState.next(true);
      }
    })
  }
   login() {
    return this.storage.set(TOKEN_KEY, 'Bearer 1234567').then(() => {
      this.authenticationState.next(true);
    });
  }
   logout() {
    return this.storage.remove(TOKEN_KEY).then(() => {
      this.authenticationState.next(false);
    });
  }
   isAuthenticated() {
    return this.authenticationState.value;
  }
 }
Also, we have added a check to the constructor so we look for a stored token once the app starts. By doing this, we can automatically change the authentication state if the user was previously logged in. In a real scenario you could add an expired check here.
To protect our pages we will later use the Angular Router and a check to see if a user is allowed to access a route. With Angular we use the Auth Guards and therefore create our own Guard where we check our service for the current state of the user.
The service implements only this one function in which we use the previous service so go ahead and change the app/services/auth-guard.service.ts to:
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { AuthenticationService } from './authentication.service';
 @Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
   constructor(public auth: AuthenticationService) {}
   canActivate(): boolean {
    return this.auth.isAuthenticated();
  }
}
Using these guards is the easiest way to protect pages or URLs of your app so users can’t access them without the proper conditions!
App Routing Logic
With Ionic 4 we can now use the standard Angular routing and therefore we create a routing configuration for our app now. The top routing allows to navigate to the register and login page without any checks, but behind the members path every pages will go through the canActivate check so they can only be access once a user is authenticated!
You could also add this checks to every single route, but having all of the routes you want to protect within one child routing module helps to save some code and structure your app better.
First of all change the already created app/app-routing.module.ts to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { AuthGuardService } from './services/auth-guard.service';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
 const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', loadChildren: './public/login/login.module#LoginPageModule' },
  { path: 'register', loadChildren: './public/register/register.module#RegisterPageModule' },
  {
    path: 'members',
    canActivate: [AuthGuardService],
    loadChildren: './members/member-routing.module#MemberRoutingModule'
  },
];
 @NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
All the pages use lazy loading therefore we are using the files plus a hash and the name of the module.
For the last route with the auth guard we are also not loading the real module but another routing, the routing for the members area. We’ve created this additional file with the Angular CLI and inside we only need to reference the Dashboard, so go ahead and change the app/members/member-routing.module.ts to:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
 const routes: Routes = [
  { path: 'dashboard', loadChildren: './dashboard/dashboard.module#DashboardPageModule' }
];
 @NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class MemberRoutingModule { }
Notice that this is a child routing and therefore the routes are added to the router with forChild()!
Finally, we can influence our routing logic at the top of the app like you might have seen in v3 in most Firebase tutorials.
We simply subscribe to our own authentication state and if a user becomes authenticated, we automatically switch to the inside area or otherwise for a logged out user back to the login.
To change the according pages we use the Angular Router and navigate to the appropriate pages. Add the code to your app/app.component.ts like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { Router } from '@angular/router';
import { AuthenticationService } from './services/authentication.service';
import { Component } from '@angular/core';
 import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
 @Component({
  selector: 'app-root',
  templateUrl: 'app.component.html'
})
export class AppComponent {
  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private authenticationService: AuthenticationService,
    private router: Router
  ) {
    this.initializeApp();
  }
   initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
       this.authenticationService.authenticationState.subscribe(state => {
        if (state) {
          this.router.navigate(['members', 'dashboard']);
        } else {
          this.router.navigate(['login']);
        }
      });
     });
  }
}
Now the app will automatically change pages on login or logout, and we don’t need to navigate from the single pages as all logic is already available at this place.
Public App Pages
We have all logic in place but we still need a few buttons and functions to navigate around our Ionic app. First of all we start with the login and two buttons.
The first will call a function while the second will directly navigate to the register page using a href. Yes, there are many ways to navigate around!
You can put the code right to your app/public/login/login.page.html:
<ion-header>
  <ion-toolbar>
    <ion-title>Login</ion-title>
  </ion-toolbar>
</ion-header>
 <ion-content padding>
  <ion-button (click)="login()" expand="block">Login</ion-button>
  <ion-button expand="block" color="secondary" href="/register" routerDirection="forward">Register</ion-button>
</ion-content>
The login is no magic so add our service and call the function once the user hits login. Again, normally you would have the input fields and pass the value to your service but we don’t need that logic right now. Therefore, just add the little changes to your app/public/login/login.page.ts:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { AuthenticationService } from './../../services/authentication.service';
import { Component, OnInit } from '@angular/core';
 @Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
   constructor(private authService: AuthenticationService) { }
   ngOnInit() {
  }
   login() {
    this.authService.login();
  }
 }
The register page is more or less pushed like with v3 but we don’t get the back button automatically so we need to add it to our page. Also, you can specify a defaultHref so whenever someone directly visits the register page the back button would appear and allow navigating back to the login!
To get the button, simple add it like this to your app/public/register/register.page.html:
<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
        <ion-back-button defaultHref="/login"></ion-back-button>
    </ion-buttons>
    <ion-title>Register</ion-title>
  </ion-toolbar>
</ion-header>
 <ion-content padding>
 </ion-content>
That’s all for the public pages, let’s finish with the inside area!
Private Member App Pages
Just like we did with the login before we can now add a button to the dashboard to log a user out again and there’s not much to do right now.
Open your app/members/dashboard/dashboard.page.html and add the button like this:
<ion-header>
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-button (click)="logout()">
        <ion-icon slot="icon-only" name="log-out"></ion-icon>
      </ion-button>
    </ion-buttons>
    <ion-title>My Dashboard</ion-title>
  </ion-toolbar>
</ion-header>
 <ion-content padding>
 </ion-content>
Finally, again, just one more line of code to call our service and the rest of the logic will be handled through the Subject in the background, therefore finish this tutorial by changing your app/members/dashboard/dashboard.page.ts:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { AuthenticationService } from './../../services/authentication.service';
import { Component, OnInit } from '@angular/core';
 @Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.page.html',
  styleUrls: ['./dashboard.page.scss'],
})
export class DashboardPage implements OnInit {
   constructor(private authService: AuthenticationService) { }
   ngOnInit() {
  }
   logout() {
    this.authService.logout();
  }
}
And that’s how you build a simple login flow with Ionic 4 and the Angular router!
Conclusion
With the closer integration of Angular inside Ionic 4 we can now use the full power of the CLI or great features like Guards, routing and more things we’ll talk about soon.
This basic Ionic login example is of course not a replacement or real authentication example, so if you want to see it in action with a JWT server and real tokens just let me know below!
You can also find a video version of this article below.
youtube
Get the free 7 day Ionic 4 Crash Course to learn how to:
Get started with Ionic
Build a Tab Bar navigation
Make HTTP calls to a REST API
Store Data inside your app
Use Cordova plugins
Style your Ionic app
The course is free, so there's nothing you can lose!
Success! Now check your email to confirm your subscription.
via Devdactic https://ift.tt/2ChQ7dt
0 notes