Angular 14 JWT User Authentication Example Tutorial

Add the auth0 configuration variables to express

🛠 Create a .env file for the API Server under the auth0-express-js-sample directory:

touch .env

🛠 Populate this auth0-express-js-sample/.env file as follows:

App component ts file

The app component is the root component of the application, it defines the root tag of the app as <app></app> with the selector property of the @Component decorator.

App module

app.module.ts file with all the components, modules, services imported and bootstrapped here in this file. It define the root module of the application along with metadata about the module

import { BrowserModule } from‘@angular/platform-browser’;

import { NgModule } from‘@angular/core’;

import { ReactiveFormsModule } from‘@angular/forms’;

import { HttpClientModule, HTTP_INTERCEPTORS } from‘@angular/common/http’;

import { BrowserAnimationsModule } from‘@angular/platform-browser/animations’;

import { ToastrModule } from‘ngx-toastr’;

// services

import { InterceptorService } from‘./_services/interceptor.service’;

import { UserService } from‘./_services/user.service’;

 

import { AppRoutingModule } from‘./app-routing.module’;

import { AppComponent } from‘./app.component’;

import { LoginComponent } from‘./login/login.component’;

import { RegisterComponent } from‘./register/register.component’;

import { HomeComponent } from‘./home/home.component’;

 

@NgModule({

declarations: [

AppComponent,

LoginComponent,

RegisterComponent,

HomeComponent

],

imports: [

BrowserModule,

AppRoutingModule,

ReactiveFormsModule,

HttpClientModule,

BrowserAnimationsModule, // required animations module

ToastrModule.forRoot()

],

providers: [UserService,{ provide:HTTP_INTERCEPTORS, useClass:InterceptorService, multi:true }], //

bootstrap: [AppComponent]

})

exportclassAppModule { }

App routing file

Routing for the Angular app is configured as an array of Routes, each component is mapped to a path so the Angular Router knows which component to display based on the URL in the browser address bar. The home route is secured by passing the AuthGuard to the canActivate property of the route.

import { NgModule } from‘@angular/core’;

import { Routes, RouterModule } from‘@angular/router’;

import { AuthGuard } from‘./_helpers/auth.guard’;

 

/**Componenets */

import { LoginComponent } from‘./login/login.component’;

import { RegisterComponent } from‘./register/register.component’;

import { HomeComponent } from‘./home/home.component’;

 

constroutes: Routes = [

{ path:, component:HomeComponent, canActivate: [AuthGuard] },

{

path:‘login’,

component:LoginComponent

},

{

path:‘register’,

component:RegisterComponent

},

{ path:‘**’, redirectTo: }

 

];

 

@NgModule({

imports: [RouterModule.forRoot(routes)],

exports: [RouterModule]

})

exportclassAppRoutingModule { }

Auth guard

Path: /src/app/_helpers/auth.guard.ts

Auth0 and angular connection set

You have completed setting up an authentication service that your Angular application can consume. All that is left is for you to continue building up the starter project throughout this tutorial by adding security components and features.

Feel free to dive deeper into the Auth0 Documentation to learn more about how Auth0 helps you save time on implementing and managing identity.

Authentication service

Path: /src/app/_services/authentication.service.ts

Basic authentication interceptor

Path: /src/app/_helpers/basic-auth.interceptor.ts

Calling an api

This section focuses on showing you how to get an access token in your Angular application and how to use it to make API calls to protected API endpoints.

Configure an auth0 application

A free account offers you:

Create a communication bridge between angular and auth0

When you use Auth0, there’s no need to build login forms. Auth0 offers a Universal Login page to reduce the overhead of adding and managing authentication.

Create a communication bridge between express and auth0

This process is similar to how you connected Angular with Auth0.

🛠 Head to the APIs section in the Auth0 Dashboard, and click the “Create API” button.

🛠 Then, in the form that Auth0 shows:

Auth0 Express Sample
  • Set its Identifier value:

Create a login button

🛠 Create a LoginButtonComponent under the src/components/ directory using the Angular CLI:

ng generate component components/login-button --inlineStyle --skipTests

Create a logout button

🛠 Create a LogoutButtonComponent under the src/components/ directory as follows:

ng generate component components/logout-button --inlineStyle --skipTests

Get the express api demo

🛠 Open a new terminal window and clone the auth0-express-js-sample repo somewhere in your system. Ensure that you clone it outside your Angular project directory.

Get the starter application

Look for the 🛠️️ emoji if you’d like to skim through the content while focusing on the build steps.

We have created a starter project using the Angular CLI to help you learn Angular security concepts through hands-on practice. The starter project uses a custom Bootstrap theme to style and layout the application so that you can focus on building and wiring Angular components.

🛠 As such, clone the auth0-angular-sample repository on its starter branch to get started:

Global less/css styles

Path: /src/styles.less

The global styles file contains LESS/CSS styles that are applied globally throughout the application.

/* You can add global styles to this file, and also import other style files */
a { cursor: pointer }

Install the auth0 angular sdk

🛠 Execute the following command:

ng add @auth0/auth0-angular

The Auth0 Angular SDK exposes several methods, variables, and types that help you integrate Auth0 with your Angular application idiomatically, including an authentication module and service.

Interceptor service

Interceptors provide a mechanism to intercept and/or mutate outgoing requests or incoming responses. They are very similar to the concept of middleware with a framework like Express, except for the frontend. Interceptors can be really useful for features like caching and logging

Main (bootstrap) file

Path: /src/main.ts

The main file is the entry point used by angular to launch and bootstrap the application.

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
    enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
    .catch(err => console.error(err));

Main index html file

Path: /src/index.html

The main index.html file is the initial page loaded by the browser that kicks everything off. The Angular CLI (with Webpack under the hood) bundles all of the compiled javascript files together and injects them into the body of the index.html page so the scripts can be loaded and executed by the browser.

Npm package.json

Path: /package.json

Production environment config

Path: /src/environments/environment.prod.ts

The production environment config contains variables required to run the application in production. This enables you to build the application with a different configuration for each different environment (e.g. production & development) without updating the app code.

When you build the application for production with the command ng build –prod, the output environment.ts is replaced with environment.prod.ts.

Protecting routes

From all the sections in this guide, this one is the easiest to implement thanks to the robustness of the Angular Router. The Auth0 Angular SDK exposes an AuthGuard that you can use to protect routes.

🛠 Open src/app/app-routing.module.ts and update it as follows:

Register component ts file

File with the logical part of the registration process. The registerForm: FormGroup object defines the form controls and validators and is used to access data entered into the form.

import { Component, OnInit } from‘@angular/core’;

import { FormBuilder, FormGroup, Validators } from‘@angular/forms’;

import { Router } from‘@angular/router’;

import { ToastrService } from‘ngx-toastr’;

 

import { UserService } from‘../_services/user.service’;

@Component({

selector:‘app-register’,

templateUrl:‘./register.component.html’

})

exportclassRegisterComponentimplementsOnInit {

 

constructor(

privateformBuilder: FormBuilder,

privaterouter: Router,

privateuserService: UserService,

privatetoastr: ToastrService

) { }

registerForm: FormGroup;

loading = false;

submitted = false;

 

ngOnInit() {

this.registerForm = this.formBuilder.group({

firstName: [, Validators.required],

lastName: [, Validators.required],

phone: [, Validators.required],

email: [, [Validators.required,Validators.email]],

password: [, [Validators.required, Validators.minLength(6)]]

});

}

 

getfval() { returnthis.registerForm.controls; }

 

onFormSubmit(){

this.submitted = true;

// return for here if form is invalid

if (this.registerForm.invalid) {

return;

}

this.loading = true;

this.userService.register(this.registerForm.value).subscribe(

(data)=>{

alert(‘User Registered successfully!!’);

this.router.navigate([‘/login’]);

},

(error)=>{

this.toastr.error(error.error.message, ‘Error’);

this.loading = false;

}

)

 

}

 

}

Set up the auth0 angular sdk

🛠 You need to follow these steps to integrate the Auth0 Angular SDK with your Angular application.

Typescript tsconfig.json

Path: /tsconfig.json

Похожее:  Картастрелка РФ проверить баланс по номеру карты

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *