Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»Flask»User Authentication With Angular 4 and Flask
    Flask

    User Authentication With Angular 4 and Flask

    March 14, 2023No Comments19 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    List of Subjects

    • Auth Workflow
    • Project Setup
    • Auth Component
    • Bootstrap Style
    • Auth Service
      • Sanity Check
      • User Login
      • User Registration
    • Server-side Setup
    • Sanity Check
    • Auth Login
    • Auth Register
    • Local Storage
    • User Status
    • Route Restriction
    • What’s Next?

    We’ll show you how to integrate Angular 4 with Flask to provide token-based authentication (using JSON Web Tokens) in this step-by-step guide.

    Principal Dependents:

    1. Angular v4.2.4 (via Angular CLI v1.3.2)
    2. Flask v0.12
    3. Python v3.6.2

    Authentique Process Flow

    This is the whole user authentication procedure:

    1. Client logs in and the credentials are sent to the server
    2. If the credentials are correct, the server generates a token and sends it as a response to the client
    3. Client receives and stores the token in Local Storage
    4. Client then sends token to server on subsequent requests within the request header

    Project Initialization

    To get started, make sure Angular CLI is installed everywhere:

    $ npm install -g @angular/cli@1.3.2
    

    Then, make a standard starting point for a brand new Angular 4 project:

    $ ng new angular4-auth
    

    Launch the programme after all its prerequisites have been set up:

    $ cd angular4-auth
    $ ng serve
    

    Your programme will need a few of minutes to compile and build. After that, you may verify the application’s functionality by going to http://localhost:4200.

    You may quickly assess the project’s structure by opening it in your preferred code editor and skimming through it:

    ├── e2e
    │   ├── app.e2e-spec.ts
    │   ├── app.po.ts
    │   └── tsconfig.e2e.json
    ├── karma.conf.js
    ├── package.json
    ├── protractor.conf.js
    ├── src
    │   ├── app
    │   │   ├── app.component.css
    │   │   ├── app.component.html
    │   │   ├── app.component.spec.ts
    │   │   ├── app.component.ts
    │   │   └── app.module.ts
    │   ├── assets
    │   ├── environments
    │   │   ├── environment.prod.ts
    │   │   └── environment.ts
    │   ├── favicon.ico
    │   ├── index.html
    │   ├── main.ts
    │   ├── polyfills.ts
    │   ├── styles.css
    │   ├── test.ts
    │   ├── tsconfig.app.json
    │   ├── tsconfig.spec.json
    │   └── typings.d.ts
    ├── tsconfig.json
    └── tslint.json
    

    The “src” folder has all of the client-side code, while the “app” folder contains the Angular application.

    Remember to remember the AppModule that is located in app.module.ts. The Angular application needs this in order to get started. Metadata that instructs Angular how to operate the app is gathered by the @NgModule decorator. Everything we make during this course will be stored under this object.

    Then, make sure you have a firm understanding of the framework of the programme.

    WARNING: Are you new to Angular 4? The created app from the CLI adheres to the recommended structure described in the Angular Style Guide and the Angular4Crud Tutorial, both of which you should go through before getting started.

    Did you discover a fresh Git repository was created when you used the command line interface? It is not required to create a new Github repository and change the remote:

    $ git remote set-url origin <newurl>
    

    , however doing so is recommended.

    Let’s plug in a fresh part right now…

    Component for Authorization Authorization

    Create a new Login component through the command line first:

    $ ng generate component components/login
    

    This created the necessary directories and files for the components and connected them to app.module.ts. To continue, please update the login.component.ts file to read:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    
    export class LoginComponent {
      test: string = 'just a test';
    }
    

    The code above will appear quite strange to you if you have never used TypeScript before. To this day, Angular 4 applications are almost exclusively written in TypeScript, a statically typed superset of JavaScript that compiles to plain JavaScript.

    In Angular 4, a component is defined by decorating a config object with the @Component decorator. In this example, we’re taking advantage of code reuse by importing classes from the @angular/core package, which contains the Component class we’ll be using later. To make the LoginComponent class, which serves as the component’s controller, accessible to other classes through the import mechanism, we utilise the export operator.

    To the login.component.html, add the following code:

    <h1>Login</h1>
    
    <p>{{test}}</p>
    

    Next, set up the routes in the app.module.ts file using the RouterModule:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { RouterModule } from '@angular/router';
    
    import { AppComponent } from './app.component';
    import { LoginComponent } from './components/login/login.component';
    
    @NgModule({
      declarations: [
        AppComponent,
        LoginComponent,
      ],
      imports: [
        BrowserModule,
        RouterModule.forRoot([
          { path: 'login', component: LoginComponent }
        ])
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    
    export class AppModule { }
    

    The last step in configuring routing is to replace all HTML in the app.component.html file with the router-outlet> element.

    <router-outlet></router-outlet>
    

    If you haven’t already, type ng serve into the terminal and go to http://localhost:4200/login. If everything went well, you should have seen the trial message.

    Bootstrap Methodology

    Modify the index.html by using Bootstrap and surrounding the app-root>/app-root> with a container to immediately inject some visual flair:

    $ ng new angular4-auth
    

    0

    When you make a change and hit “save,” the app should immediately refresh.

    Auth. Service

    Let’s go on to developing a global service to manage user registration, login, and logout:

    $ ng new angular4-auth
    

    1

    Change the following into the auth.service.ts file:

    $ ng new angular4-auth
    

    2

    Do you still remember the Angular 1 provider system? These were objects with a global scope and a single state. If an object had a provider injection, then whenever the provider’s data changed, the injected object would get the new data. Providers continue to exhibit their unique behaviour in Angular 4, and they are now declared using the @Injectable decorator.

    Logic vs. Sanity Test

    Let’s make sure the AuthService infrastructure is set up properly before we add any major new features to it. To do so, inject the service and invoke test() in the login.component.ts file:

    $ ng new angular4-auth
    

    3

    There are some new ideas and terminology that we’ve presented. To initialise a new instance of a class, we call its function Object() { [native code] }() function. To inject a provider (such as AuthService), we use the class’s function Object() { [native code] }() to feed in the necessary information. TypeScript’s private keyword allows us to keep some variables hidden from the public. Defining a private variable inside the class and assigning its value in the function Object() { [native code] } is a time saver. After being provided into the function Object() { [native code] }, the auth variable becomes available to this object.

    In order to guarantee that a ngOnInit() method is defined, we have chosen to implement the OnInit interface. By taking use of OnInit, we can guarantee that our component will be contacted after the first check for changes has been made. The optimal time to setup data that depends on other Angular classes is in this method, since it is called just once during the component’s initialization.

    In contrast to components, which may be installed automatically, services must be imported and configured on the @NgModule manually. The AuthService must be imported in app.module.ts and added to the providers for this to function.

    $ ng new angular4-auth
    

    4

    Start the server by going to http://localhost:4200/login in a web browser. On the JavaScript console, you should see evidence of progress.

    Entering the Login Information

    Changes to the AuthService should be made as follows for handling user logins.

    $ ng new angular4-auth
    

    5

    We make use of the in-built Angular classes Headers and Http to manage our AJAX requests to the server.

    Import the HttpModule by updating the app.module.ts file.

    $ ng new angular4-auth
    

    6

    Here, an AJAX request is being sent through the Http service to the /user/login endpoint. A promise object is returned.

    WARNING: In the LoginComponent, delete the console.log(this.auth.test()); line.

    A New User Must Register

    Let’s also implement user registration, which serves a similar purpose to user login. Keep in mind the register function while you update src/app/services/auth.service.ts:

    $ ng new angular4-auth
    

    7

    We need to implement a backend to test this, however.

    Initiation on the Server

    We’ll be use the final product from a previous blog article, Token-Based Authentication with Flask, for the server-side of things. The code is hosted in the flask-jwt-auth repository and is available for review.

    It’s OK to use your own server, but you’ll need to change the baseURL in the AuthService.

    Make a copy of the project’s directory structure in a new terminal:

    $ ng new angular4-auth
    

    8

    To get started with the project, read the README and follow its instructions, making sure that all of the tests pass before proceeding. To activate the server, do python manage.py runserver; it will start listening on port 5000.

    Logic vs. Sanity Test

    Update LoginComponent so that it communicates with the service’s login and register functions for testing purposes.

    $ ng new angular4-auth
    

    9

    When the user logs in, the token should appear in the JavaScript console when you refresh http://localhost:4200/login in the browser.

    $ cd angular4-auth
    $ ng serve
    

    0

    Upgrade to Authorized User Account Login login.component.html:

    $ cd angular4-auth
    $ ng serve
    

    1

    Mind the form. To save the information entered into the form fields in the controller, we utilised the [(ngModel)] directive. The onLogin() function is called after the form is submitted thanks to the ngSubmit directive.

    Let’s go ahead and modify the component code by include onLogin():

    $ cd angular4-auth
    $ ng serve
    

    2

    In case you have Angular’s web server up and running, you should get an error. Browser error: Unable to load required module ‘../../models/user’. This code will not run until a User model is created.

    src/app/models/user.ts:

    $ cd angular4-auth
    $ ng serve
    

    3 New:

    $ cd angular4-auth
    $ ng serve
    

    4

    Both email and password are attributes of our User model. To indicate that it is not required to initialise User with email and password values, the special operator? is used. In Python, this corresponds to the following module:

    $ cd angular4-auth
    $ ng serve
    

    5

    Make sure auth.service.ts is updated as well to make use of the new object.

    $ cd angular4-auth
    $ ng serve
    

    6

    Finally, this. The app.module.ts file requires an import of the FormsModule.

    $ cd angular4-auth
    $ ng serve
    

    7

    In order to access the service, we collect the user’s email address and password at the time of form submission and send them to the login() function.

    Try it with

    • email: michael@realpython.com
    • password: michael

    and see if it works.

    Token use should again result in a successful output in the java script console.

    Permission to Register

    We must also implement a component for user registration, same as we did with the login form. Create a new Register part to begin.

    $ cd angular4-auth
    $ ng serve
    

    8

    Code correction in src/app/components/register/register.component.html, line 29

    After that, do the following in src/app/components/register/register.component.ts:

    ├── e2e
    │   ├── app.e2e-spec.ts
    │   ├── app.po.ts
    │   └── tsconfig.e2e.json
    ├── karma.conf.js
    ├── package.json
    ├── protractor.conf.js
    ├── src
    │   ├── app
    │   │   ├── app.component.css
    │   │   ├── app.component.html
    │   │   ├── app.component.spec.ts
    │   │   ├── app.component.ts
    │   │   └── app.module.ts
    │   ├── assets
    │   ├── environments
    │   │   ├── environment.prod.ts
    │   │   └── environment.ts
    │   ├── favicon.ico
    │   ├── index.html
    │   ├── main.ts
    │   ├── polyfills.ts
    │   ├── styles.css
    │   ├── test.ts
    │   ├── tsconfig.app.json
    │   ├── tsconfig.spec.json
    │   └── typings.d.ts
    ├── tsconfig.json
    └── tslint.json
    

    0

    Place the following code at the end of app.module.ts to create a route handler:

    Try creating a new account and seeing how it works!

    Data Storing Close to Home

    Replace console.log(user.json()); with localStorage.setItem(‘token’, user.data.token); in src/app/components/login/login.component.ts:

    ├── e2e
    │   ├── app.e2e-spec.ts
    │   ├── app.po.ts
    │   └── tsconfig.e2e.json
    ├── karma.conf.js
    ├── package.json
    ├── protractor.conf.js
    ├── src
    │   ├── app
    │   │   ├── app.component.css
    │   │   ├── app.component.html
    │   │   ├── app.component.spec.ts
    │   │   ├── app.component.ts
    │   │   └── app.module.ts
    │   ├── assets
    │   ├── environments
    │   │   ├── environment.prod.ts
    │   │   └── environment.ts
    │   ├── favicon.ico
    │   ├── index.html
    │   ├── main.ts
    │   ├── polyfills.ts
    │   ├── styles.css
    │   ├── test.ts
    │   ├── tsconfig.app.json
    │   ├── tsconfig.spec.json
    │   └── typings.d.ts
    ├── tsconfig.json
    └── tslint.json
    

    2 to save the token in Local Storage.

    Add this line of code to src/app/components/register/register.component.ts:

    ├── e2e
    │   ├── app.e2e-spec.ts
    │   ├── app.po.ts
    │   └── tsconfig.e2e.json
    ├── karma.conf.js
    ├── package.json
    ├── protractor.conf.js
    ├── src
    │   ├── app
    │   │   ├── app.component.css
    │   │   ├── app.component.html
    │   │   ├── app.component.spec.ts
    │   │   ├── app.component.ts
    │   │   └── app.module.ts
    │   ├── assets
    │   ├── environments
    │   │   ├── environment.prod.ts
    │   │   └── environment.ts
    │   ├── favicon.ico
    │   ├── index.html
    │   ├── main.ts
    │   ├── polyfills.ts
    │   ├── styles.css
    │   ├── test.ts
    │   ├── tsconfig.app.json
    │   ├── tsconfig.spec.json
    │   └── typings.d.ts
    ├── tsconfig.json
    └── tslint.json
    

    3

    If the token is still in the user’s possession, they are regarded to be authenticated. And that token may be utilised when an AJAX request is required.

    Please take note that in addition to the token, you may also save the user’s id and email address in Local Storage. Upon user login, that data may simply be sent back by updating the server.

    Put it to the test. After signing in, check to see whether the token is still stored in local storage.

    Condition of the User

    We can verify login persistence by adding a new view that checks the user’s login and the token’s validity.

    Include the next procedure in AuthService:

    ├── e2e
    │   ├── app.e2e-spec.ts
    │   ├── app.po.ts
    │   └── tsconfig.e2e.json
    ├── karma.conf.js
    ├── package.json
    ├── protractor.conf.js
    ├── src
    │   ├── app
    │   │   ├── app.component.css
    │   │   ├── app.component.html
    │   │   ├── app.component.spec.ts
    │   │   ├── app.component.ts
    │   │   └── app.module.ts
    │   ├── assets
    │   ├── environments
    │   │   ├── environment.prod.ts
    │   │   └── environment.ts
    │   ├── favicon.ico
    │   ├── index.html
    │   ├── main.ts
    │   ├── polyfills.ts
    │   ├── styles.css
    │   ├── test.ts
    │   ├── tsconfig.app.json
    │   ├── tsconfig.spec.json
    │   └── typings.d.ts
    ├── tsconfig.json
    └── tslint.json
    

    4

    Remember Authorization: Holder + token. The request includes something called a Bearer schema. We only care whether the Authorization header is there and the token is legitimate on the server. Is this programme code accessible from the backend?

    Next, make a brand-new Status part:

    ├── e2e
    │   ├── app.e2e-spec.ts
    │   ├── app.po.ts
    │   └── tsconfig.e2e.json
    ├── karma.conf.js
    ├── package.json
    ├── protractor.conf.js
    ├── src
    │   ├── app
    │   │   ├── app.component.css
    │   │   ├── app.component.html
    │   │   ├── app.component.spec.ts
    │   │   ├── app.component.ts
    │   │   └── app.module.ts
    │   ├── assets
    │   ├── environments
    │   │   ├── environment.prod.ts
    │   │   └── environment.ts
    │   ├── favicon.ico
    │   ├── index.html
    │   ├── main.ts
    │   ├── polyfills.ts
    │   ├── styles.css
    │   ├── test.ts
    │   ├── tsconfig.app.json
    │   ├── tsconfig.spec.json
    │   └── typings.d.ts
    ├── tsconfig.json
    └── tslint.json
    

    5

    Code@@@36 src/app/components/status/status.component.html: Build the HTML template

    Then edit status.component.ts in the app’s source folder to read:

    ├── e2e
    │   ├── app.e2e-spec.ts
    │   ├── app.po.ts
    │   └── tsconfig.e2e.json
    ├── karma.conf.js
    ├── package.json
    ├── protractor.conf.js
    ├── src
    │   ├── app
    │   │   ├── app.component.css
    │   │   ├── app.component.html
    │   │   ├── app.component.spec.ts
    │   │   ├── app.component.ts
    │   │   └── app.module.ts
    │   ├── assets
    │   ├── environments
    │   │   ├── environment.prod.ts
    │   │   └── environment.ts
    │   ├── favicon.ico
    │   ├── index.html
    │   ├── main.ts
    │   ├── polyfills.ts
    │   ├── styles.css
    │   ├── test.ts
    │   ├── tsconfig.app.json
    │   ├── tsconfig.spec.json
    │   └── typings.d.ts
    ├── tsconfig.json
    └── tslint.json
    

    7

    Lastly, edit the app.module.ts file to include a new route handler:

    ├── e2e
    │   ├── app.e2e-spec.ts
    │   ├── app.po.ts
    │   └── tsconfig.e2e.json
    ├── karma.conf.js
    ├── package.json
    ├── protractor.conf.js
    ├── src
    │   ├── app
    │   │   ├── app.component.css
    │   │   ├── app.component.html
    │   │   ├── app.component.spec.ts
    │   │   ├── app.component.ts
    │   │   └── app.module.ts
    │   ├── assets
    │   ├── environments
    │   │   ├── environment.prod.ts
    │   │   └── environment.ts
    │   ├── favicon.ico
    │   ├── index.html
    │   ├── main.ts
    │   ├── polyfills.ts
    │   ├── styles.css
    │   ├── test.ts
    │   ├── tsconfig.app.json
    │   ├── tsconfig.spec.json
    │   └── typings.d.ts
    ├── tsconfig.json
    └── tslint.json
    

    8

    Prepared to be put to the test? Visit http://localhost:4200/status after logging in. To verify the existence of a token in the local storage, please enter the following:

    ├── e2e
    │   ├── app.e2e-spec.ts
    │   ├── app.po.ts
    │   └── tsconfig.e2e.json
    ├── karma.conf.js
    ├── package.json
    ├── protractor.conf.js
    ├── src
    │   ├── app
    │   │   ├── app.component.css
    │   │   ├── app.component.html
    │   │   ├── app.component.spec.ts
    │   │   ├── app.component.ts
    │   │   └── app.module.ts
    │   ├── assets
    │   ├── environments
    │   │   ├── environment.prod.ts
    │   │   └── environment.ts
    │   ├── favicon.ico
    │   ├── index.html
    │   ├── main.ts
    │   ├── polyfills.ts
    │   ├── styles.css
    │   ├── test.ts
    │   ├── tsconfig.app.json
    │   ├── tsconfig.spec.json
    │   └── typings.d.ts
    ├── tsconfig.json
    └── tslint.json
    

    9

    Why? But, if you look into it further on the server side, you will see that the token is only valid for 5 seconds in project/server/models. py:

    $ git remote set-url origin <newurl>
    

    0

    Bring it up to date by 1 day:

    $ git remote set-url origin <newurl>
    

    1 Have another round of testing done. The result should look like this:

    $ git remote set-url origin <newurl>
    

    2.

    Once a person successfully registers or signs in, let’s take them to a status page. To fix this, please edit login.component.ts in src/app/components/login.

    Then, edit the following line in register.component.ts, located in src/app:

    $ git remote set-url origin <newurl>
    

    4

    Try it out and see if it works!

    Limitations on Travel

    There is currently no need for a user to be logged in order to access any route. It’s important to limit access to certain paths depending on whether or not the user is signed in.

    1. / – no restrictions
    2. /login – restricted when logged in
    3. /register – restricted when logged in
    4. /status – restricted when not logged in

    Depending on whether you want to drive the user to the status view or the login page, you can do so by appending EnsureAuthenticated or LoginRedirect to each route.

    Initiate two brand-new offerings, namely:

    $ git remote set-url origin <newurl>
    

    5

    In the file ensure-authenticated.service.ts, replace the following with the new code:

    $ git remote set-url origin <newurl>
    

    6

    Also, edit the login-redirect.service.ts file as follows:

    $ git remote set-url origin <newurl>
    

    7

    At last, import and set up the new services by updating the app.module.ts file:

    $ git remote set-url origin <newurl>
    

    8

    Please take note of how we are extending the canActivate attribute of routes to include our services. The canActivate array’s services are used by the routing system to decide whether or not to show the requested URL route. If the user is signed in while accessing the route in question, they will be routed to the status view. If a user tries to visit a URL that needs authentication and the corresponding EnsureAuthenticated service is present, they will be redirected to the login screen.

    Perform one final check.

    So, Now What?

    Adding support for JSON Web Tokens-based authentication to an existing Angular 4 + Flask project was the subject of this tutorial.

    The following step is…

    The following endpoints may be used to replace the Flask backend with an other web framework, such as Django or Bottle:

    • /auth/register
    • /auth/login
    • /auth/logout
    • /auth/user

    Check out this video series to learn all you need to know to create a fully functional Python web app using Flask:

    Feel free to ask questions and make comments here. The completed code is available in the angular4-auth repository.

    Check off as finished

    Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Language User Authentication With Angular 4 and Flask
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticlePython Sets
    Next Article Fast Flexible Easy and Intuitive How to Speed Up Your pandas Projects

    Related Posts

    python

    Plot With Pandas Python Data Visualization Basics

    March 27, 2023
    python

    Defining and Calling Python Functions

    March 27, 2023
    python

    BreadthFirst Search in Python

    March 27, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.