简体   繁体   English

针对静态API的角度登录/身份验证

[英]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: 我已经在针对硬编码凭据编写的angular应用程序中创建了基本身份验证系统-参见下文:

app.js 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 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 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. 我现在想做的是,通过将数据发布到服务器/登录名来针对api调用检查用户名和密码,如果成功,则返回访问令牌,然后将其存储在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
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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