[英]Angular login/authentication against restful API
我已經在針對硬編碼憑據編寫的angular
應用程序中創建了基本身份驗證系統-參見下文:
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');
}
};
});
這可行。 我現在想做的是,通過將數據發布到服務器/登錄名來針對api調用檢查用戶名和密碼,如果成功,則返回訪問令牌,然后將其存儲在cookie中。 此時,用戶可以訪問應用程序的其余部分。
如果憑據失敗,則會進行驗證,從而阻止用戶登錄。
做這個的最好方式是什么?
首先檢查這個網址
您的代碼如下所示:
$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.