简体   繁体   中英

Angular login/authentication against restful API

I have created a basic authentication system in an angular app which is written against hardcoded credentials - see below:

app.js

/* global app:true */
/* exported app */
'use strict';

/**
 * @ngdoc overview
 * @name WebAppApp
 * @description
 * # WebAppApp
 *
 * Main module of the application.
 */
var app = angular
  .module('WebAppApp', [
    'ngAnimate',
    'ngAria',
    'ngCookies',
    'ngMessages',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/login.html',
        controller: 'loginCtrl',
        controllerAs: 'login'
      })
      .when('/home', {
        templateUrl: 'views/home.html'
        //controller: 'loginCtrl',
        //controllerAs: 'login'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

login.html

<form ng-submit="submit()">
  Username: <input type="text" id="username" ng-model="username" /><br>
  Password: <input type="password" id="password" ng-model="password" /><br>
  <input type="submit" value="Submit" />
</form>

login.js

'use strict';

//app global variable
//this is hte controller that handles post requests
app.controller('loginCtrl', function ($scope, $location) {

    $scope.submit = function(){
        var uname = $scope.username;
        var password = $scope.password;

        if($scope.username == 'admin' && $scope.password == 'admin'){

            $location.path('/home');

        } else {

            alert('username or password is wrong');
        }

    };

});

This works. What I want to do now, is check the username and password against an api call by posting the data to the server /login, if successful an access token is returned, and is then stored inside of a cookie. At which point the user gets access to the rest of the application.

If the credentials fails, for validation takes place preventing the user from logging in.

What is the best way to do this?

First of all check this url

Your code would look something like this:

$scope.submit = function(){
    $http.post('/login', {
        username:$scope.username,
        password:$scope.password
    }).then(function(response) {
        if (response.data=="ok") {
          //Login was ok
          $location.path("/home");
        } else {
          //Login was not ok
        } 
      }, function(response) {
           //Error happend, response.status or response.statusText have details
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM