AngularJS: Basic example to use authentication in Single Page Application

后端 未结 6 1558
余生分开走
余生分开走 2020-12-02 03:30

I am new to AngularJS and gone through their tutorial and got a feel for it.

I have a backend for my project ready where each of the REST endpoints need

6条回答
  •  粉色の甜心
    2020-12-02 04:19

    I answered a similar question here: AngularJS Authentication + RESTful API


    I've written an AngularJS module for UserApp that supports protected/public routes, rerouting on login/logout, heartbeats for status checks, stores the session token in a cookie, events, etc.

    You could either:

    1. Modify the module and attach it to your own API, or
    2. Use the module together with UserApp (a cloud-based user management API)

    https://github.com/userapp-io/userapp-angular

    If you use UserApp, you won't have to write any server-side code for the user stuff (more than validating a token). Take the course on Codecademy to try it out.

    Here's some examples of how it works:

    • How to specify which routes that should be public, and which route that is the login form:

      $routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
      $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
      $routeProvider.when('/home', {templateUrl: 'partials/home.html'});
      

      The .otherwise() route should be set to where you want your users to be redirected after login. Example:

      $routeProvider.otherwise({redirectTo: '/home'});

    • Login form with error handling:



    • Signup form with error handling:




    • Log out link:

      Log Out

      (Ends the session and redirects to the login route)

    • Access user properties:

      User properties are accessed using the user service, e.g: user.current.email

      Or in the template: {{ user.email }}

    • Hide elements that should only be visible when logged in:

      Welcome {{ user.first_name }}!

    • Show an element based on permissions:

      You are an admin

    And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API (if you use UserApp) to check if the token is valid or not.

    If you need any help, just let me know!

提交回复
热议问题