How to handle authentication in Angular JS application

前端 未结 4 673
面向向阳花
面向向阳花 2020-12-04 20:23

I am implementing an auth system in my angular js app.

What I am planning it like below:

  1. Get user info(name and pass from login form)
  2. Check w
相关标签:
4条回答
  • 2020-12-04 20:42

    I use the http-auth-interceptor. http://ngmodules.org/modules/http-auth-interceptor

    In my backend (asp.net mvc) I build a simple Authentication Service and return an http error 401 if the user is not authenticated. Then I handle the error with a login-view in the SPA site.

    0 讨论(0)
  • 2020-12-04 20:46

    I am not sure about your backend, but this is how I would do it

    • Create a separate login page (dedicated url not angular sub view or modal dialog).
    • If the user is not authenticated redirect to this login page. This is done by server redirects. This page may or may not use angular framework, as it just involves sending a user\password to server.
    • Make a POST (not AJAX request) from the login page, and verify on server.
    • On the server set the auth cookie. (Different frameworks do it differently. ASP.Net sets form authentication cookie.)
    • Once the user is authenticated redirect user to the actual angular app and load all its components.

    This saves any code require to manage authentication on client side in Angular. If the user lands on this page he is authenticated and has the cookie.

    Also default browser behavior is to send all cookies associated with a domain with each request, so you don't have to worry if angular is sending some cookie or not.

    0 讨论(0)
  • 2020-12-04 20:49

    The ideas put forth by the previous answers will work, but I think they're overkill. You don't need anything this complex.

    how I can add the cookie information while doing the next REST call

    Turn on withCredentials by default inside $httpProvider like so:

    app.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.withCredentials = true;
    }]);
    

    Then remove the wildcard (if you had one) from the CORS-related headers, and set allow-credentials, on the server side. In my case, using Python + Flask + Flask-Restful, it's super easy and looks like this:

    import Flask
    from flask_restful import Api
    app = Flask(__name__)
    api = Api(app)
    api.decorators = [cors.crossdomain(origin='http://localhost:8100', credentials=True)]
    

    Now cookies will be set and returned automatically and transparently by the browser. See these threads for more info:

    • $http response Set-Cookie not accessible
    • Angularjs $http does not seem to understand "Set-Cookie" in the response

    when user will navigate throughout the application after log in I do want to check each time isAuthenticaed true or false

    As suggested above, have the server return 401 if the auth session expires or is deleted, and use $httpInterceptor in Angular to catch this like so:

    app.config(function($httpProvider) {
        var interceptor =
            function($q, $rootScope) {
                return {
                    'response': function(response) {
                        return response;
                     },
                    'responseError': function(rejection) {
                        if (rejection.status==401) {
                            // Modify this part to suit your needs.
                            // In my case I broadcast a message which is
                            // picked up elsewhere to show the login screen.
                            if (!rejection.config.url.endsWith('/login'))
                            {
                                $rootScope.$broadcast('auth:loginRequired');
                            }
                        }
    
                        return $q.reject(rejection)
                     }
                }
            };
    
        $httpProvider.interceptors.push(interceptor);
    });
    
    0 讨论(0)
  • 2020-12-04 21:05

    (Disclosure: I'm one of the developers of UserApp)

    You could use the third-party service UserApp for this, together with the AngularJS module.

    Check out the getting started guide, or take the course on Codecademy. Here's some examples of how it works:

    • Login form with error handling:

      <form ua-login ua-error="error-msg">
          <input name="login" placeholder="Username"><br>
          <input name="password" placeholder="Password" type="password"><br>
          <button type="submit">Log in</button>
          <p id="error-msg"></p>
      </form>
      

      User info is accessed using the user service: user.current.email

      Or in the template: <span>{{ user.email }}</span>

    • Signup form with error handling:

      <form ua-signup ua-error="error-msg">
          <input name="first_name" placeholder="Your name"><br>
          <input name="login" ua-is-email placeholder="Email"><br>
          <input name="password" placeholder="Password" type="password"><br>
          <button type="submit">Create account</button>
          <p id="error-msg"></p>
      </form>
      

      ua-is-email means that the username is the same as the email.

    • 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});
      

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

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

    • Log out link:

      <a href="#" ua-logout>Log Out</a>

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

      <div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>

    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 to check if the token is valid or not.

    If you need any help, just let me know :)

    0 讨论(0)
提交回复
热议问题