Sharing Top Content from the Angular-sphere.

User Authentication With Angular 4 and Flask – Real Python

  • /app.component’; – import { LoginComponent } from declarations: [ – AppComponent, – LoginComponent, – ], – imports: [ – BrowserModule, – RouterModule.forRoot([ – { path: ‘login’, component: LoginComponent } – ]) – ], – providers: [], – bootstrap: [AppComponent] – }) – – export class AppModule { } – -…
  • Auth Service – Next, let’s create a global service to handle a user logging in, logging out, and signing up: – $ ng generate service services/auth – – Edit the auth.service.ts so that it has the following code: – import { Injectable } from class AuthService { – test(): string…
  • /app.component’; – import { LoginComponent } from { AuthService } from declarations: [ – AppComponent, – LoginComponent, – ], – imports: [ – BrowserModule, – RouterModule.forRoot([ – { path: ‘login’, component: LoginComponent } – ]) – ], – providers: [AuthService], – bootstrap: [AppComponent] – }) – – export class AppModule…
  • User Login – To handle logging a user in, update the AuthService like so: – import { Injectable } from ‘@angular/core’; – import { Headers, Http } from ‘@angular/http’; – import class AuthService { – private BASE_URL: string = ‘http://localhost:5000/auth’; – private headers: Headers = new Headers({‘Content-Type’: ‘application/json’}); – constructor(private…
  • /app.component’; – import { LoginComponent } from { AuthService } from declarations: [ – AppComponent, – LoginComponent, – ], – imports: [ – BrowserModule, – HttpModule, – RouterModule.forRoot([ – { path: ‘login’, component: LoginComponent } – ]) – ], – providers: [AuthService], – bootstrap: [AppComponent] – }) – – export…

Here we look at how to handle user authentication using JSON Web Tokens with Angular and Flask.

In this tutorial, we’ll demonstrate how to set up token-based authentication (via JSON Web Tokens) with Angular 4 and Flask.

Main Dependencies:

Angular v4.2.4 (via Angular CLI v1.3.2)

Flask v0.12

Python v3.6.2

Auth Workflow

Here’s the full user auth process:

Client logs in and the credentials are sent to the server

If the credentials are correct, the server generates a token and sends it as a response to the client

Client receives and stores the token in Local Storage

Client then sends token to server on subsequent requests within the request header

Project Setup

Start by globally installing the Angular CLI:

$ npm install -g @angular/cli@1.3.2

Then generate a new Angular 4 project boilerplate:

Fire up the app after the dependencies install:

$ cd angular4-auth

$ ng serve

It will probably take a minute or two to compile and build your application. Once done, navigate to http://localhost:4200 to ensure the app is up and running.

Open up the project in your favorite code editor, and then glance over the code:

├── e2e

│   ├── app.e2e-spec.ts

│   ├── app.po.ts

│   └──…

User Authentication With Angular 4 and Flask – Real Python