AngularJS-每个路由和控制器中的登录和身份验证



我有一个使用 yeoman、grunt 和 bower 创建的 AngularJS 应用程序。

我有一个登录页面,其中包含一个检查身份验证的控制器。如果凭据正确,我将重新路由到主页。

应用.js

'use strict';
//Define Routing for app
angular.module('myApp', []).config(['$routeProvider', '$locationProvider',
function($routeProvider,$locationProvider) {
$routeProvider
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginController'
})
.when('/register', {
templateUrl: 'register.html',
controller: 'RegisterController'
})
.when('/forgotPassword', {
templateUrl: 'forgotpassword.html',
controller: 'forgotController'
})
.when('/home', {
templateUrl: 'views/home.html',
controller: 'homeController'
})
.otherwise({
redirectTo: '/login'
});
//    $locationProvider.html5Mode(true); //Remove the '#' from URL.
}]);
angular.module('myApp').factory("page", function($rootScope){
var page={};
var user={};
page.setPage=function(title,bodyClass){
$rootScope.pageTitle = title;
$rootScope.bodylayout=bodyClass;
};
page.setUser=function(user){
$rootScope.user=user;
}
return page;
});

登录控制器.js

'use strict';
angular.module('myApp').controller('LoginController', function($scope, $location, $window,page) {
page.setPage("Login","login-layout");
$scope.user = {};
$scope.loginUser=function()
{
var username=$scope.user.name;
var password=$scope.user.password;
if(username=="admin" && password=="admin123")
{
page.setUser($scope.user);
$location.path( "/home" );
}
else
{
$scope.message="Error";
$scope.messagecolor="alert alert-danger";
}
}
});

在主页上我有

<span class="user-info">
<small>Welcome,</small>
{{user.name}}
</span>
<span class="logout"><a href="" ng-click="logoutUser()">Logout</a></span>

loginController中,我检查登录信息,如果成功,则在服务工厂中设置用户对象。我不知道这是否正确。

我需要的是,当用户登录时,它会在用户对象中设置一些值,以便所有其他页面都可以获取该值。

每当发生任何路由更改时,控制器都应检查用户是否已登录。如果没有,它应该重新路由到登录页面。此外,如果用户已登录并返回页面,则应转到主页。控制器还应检查所有路由上的凭据。

我听说过ng-cookie,但我不知道如何使用它们。

我看到的许多示例都不是很清楚,它们使用某种访问角色或其他东西。我不想这样。我只想要一个登录过滤器。 有人可以给我一些想法吗?

我的解决方案分为 3 个部分:用户的状态存储在服务中,在路由更改时监视的 run 方法中检查是否允许用户访问请求的页面,在主控制器中观察用户的状态是否更改。

app.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!Auth.isLoggedIn()) {
console.log('DENY');
event.preventDefault();
$location.path('/login');
}
else {
console.log('ALLOW');
$location.path('/home');
}
});
}]);

您应该创建一个服务(我将其命名为Auth),它将处理用户对象并具有一种方法来了解用户是否已登录。

服务

.factory('Auth', function(){
var user;
return{
setUser : function(aUser){
user = aUser;
},
isLoggedIn : function(){
return(user)? user : false;
}
}
})

从你的app.run,你应该听$routeChangeStart事件。当路由更改时,它将检查用户是否已记录(isLoggedIn方法应处理它)。如果未记录用户,它不会加载请求的路由,它会将用户重定向到正确的页面(在您的情况下登录)。

应在登录页面中使用loginController来处理登录。它应该只与Auth服务交互,并将用户设置为是否记录。

登录控制器

.controller('loginCtrl', [ '$scope', 'Auth', function ($scope, Auth) {
//submit
$scope.login = function () {
// Ask to the server, do your job and THEN set the user
Auth.setUser(user); //Update the state of the user in the app
};
}])

从主控制器中,您可以侦听用户状态是否更改并通过重定向做出反应。

.controller('mainCtrl', ['$scope', 'Auth', '$location', function ($scope, Auth, $location) {
$scope.$watch(Auth.isLoggedIn, function (value, oldValue) {
if(!value && oldValue) {
console.log("Disconnect");
$location.path('/login');
}
if(value) {
console.log("Connect");
//Do something when the user is connected
}
}, true);

这是另一种可能的解决方案,使用$stateProvider$routeProviderresolve属性。带有$stateProvider的示例:

.config(["$stateProvider", function ($stateProvider) {
$stateProvider
.state("forbidden", {
/* ... */
})
.state("signIn", {
/* ... */
resolve: {
access: ["Access", function (Access) { return Access.isAnonymous(); }],
}
})
.state("home", {
/* ... */
resolve: {
access: ["Access", function (Access) { return Access.isAuthenticated(); }],
}
})
.state("admin", {
/* ... */
resolve: {
access: ["Access", function (Access) { return Access.hasRole("ROLE_ADMIN"); }],
}
});
}])

Access根据当前用户权限解析或拒绝承诺:

.factory("Access", ["$q", "UserProfile", function ($q, UserProfile) {
var Access = {
OK: 200,
// "we don't know who you are, so we can't say if you're authorized to access
// this resource or not yet, please sign in first"
UNAUTHORIZED: 401,
// "we know who you are, and your profile does not allow you to access this resource"
FORBIDDEN: 403,
hasRole: function (role) {
return UserProfile.then(function (userProfile) {
if (userProfile.$hasRole(role)) {
return Access.OK;
} else if (userProfile.$isAnonymous()) {
return $q.reject(Access.UNAUTHORIZED);
} else {
return $q.reject(Access.FORBIDDEN);
}
});
},
hasAnyRole: function (roles) {
return UserProfile.then(function (userProfile) {
if (userProfile.$hasAnyRole(roles)) {
return Access.OK;
} else if (userProfile.$isAnonymous()) {
return $q.reject(Access.UNAUTHORIZED);
} else {
return $q.reject(Access.FORBIDDEN);
}
});
},
isAnonymous: function () {
return UserProfile.then(function (userProfile) {
if (userProfile.$isAnonymous()) {
return Access.OK;
} else {
return $q.reject(Access.FORBIDDEN);
}
});
},
isAuthenticated: function () {
return UserProfile.then(function (userProfile) {
if (userProfile.$isAuthenticated()) {
return Access.OK;
} else {
return $q.reject(Access.UNAUTHORIZED);
}
});
}
};
return Access;
}])

UserProfile复制当前用户属性,并实现$hasRole$hasAnyRole$isAnonymous$isAuthenticated方法逻辑(以及稍后解释的$refresh方法):

.factory("UserProfile", ["Auth", function (Auth) {
var userProfile = {};
var clearUserProfile = function () {
for (var prop in userProfile) {
if (userProfile.hasOwnProperty(prop)) {
delete userProfile[prop];
}
}
};
var fetchUserProfile = function () {
return Auth.getProfile().then(function (response) {
clearUserProfile();
return angular.extend(userProfile, response.data, {
$refresh: fetchUserProfile,
$hasRole: function (role) {
return userProfile.roles.indexOf(role) >= 0;
},
$hasAnyRole: function (roles) {
return !!userProfile.roles.filter(function (role) {
return roles.indexOf(role) >= 0;
}).length;
},
$isAnonymous: function () {
return userProfile.anonymous;
},
$isAuthenticated: function () {
return !userProfile.anonymous;
}
});
});
};
return fetchUserProfile();
}])

Auth负责请求服务器,以了解用户配置文件(链接到附加到请求的访问令牌):

.service("Auth", ["$http", function ($http) {
this.getProfile = function () {
return $http.get("api/auth");
};
}])

服务器在请求GET api/auth时应返回这样的 JSON 对象:

{
"name": "John Doe", // plus any other user information
"roles": ["ROLE_ADMIN", "ROLE_USER"], // or any other role (or no role at all, i.e. an empty array)
"anonymous": false // or true
}

最后,当Access拒绝一个承诺时,如果使用ui.router,将触发$stateChangeError事件:

.run(["$rootScope", "Access", "$state", "$log", function ($rootScope, Access, $state, $log) {
$rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) {
switch (error) {
case Access.UNAUTHORIZED:
$state.go("signIn");
break;
case Access.FORBIDDEN:
$state.go("forbidden");
break;
default:
$log.warn("$stateChangeError event catched");
break;
}
});
}])

如果使用ngRoute,将触发$routeChangeError事件:

.run(["$rootScope", "Access", "$location", "$log", function ($rootScope, Access, $location, $log) {
$rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
switch (rejection) {
case Access.UNAUTHORIZED:
$location.path("/signin");
break;
case Access.FORBIDDEN:
$location.path("/forbidden");
break;
default:
$log.warn("$stateChangeError event catched");
break;
}
});
}])

用户配置文件也可以在控制器中访问:

.state("home", {
/* ... */
controller: "HomeController",
resolve: {
userProfile: "UserProfile"
}
})

然后UserProfile包含服务器在请求GET api/auth时返回的属性:

.controller("HomeController", ["$scope", "userProfile", function ($scope, userProfile) {
$scope.title = "Hello " + userProfile.name; // "Hello John Doe" in the example
}])

UserProfile需要在用户登录或注销时刷新,以便Access可以使用新用户配置文件处理路由。您可以重新加载整个页面,也可以调用UserProfile.$refresh()。登录时的示例:

.service("Auth", ["$http", function ($http) {
/* ... */
this.signIn = function (credentials) {
return $http.post("api/auth", credentials).then(function (response) {
// authentication succeeded, store the response access token somewhere (if any)
});
};
}])
.state("signIn", {
/* ... */
controller: "SignInController",
resolve: {
/* ... */
userProfile: "UserProfile"
}
})
.controller("SignInController", ["$scope", "$state", "Auth", "userProfile", function ($scope, $state, Auth, userProfile) {
$scope.signIn = function () {
Auth.signIn($scope.credentials).then(function () {
// user successfully authenticated, refresh UserProfile
return userProfile.$refresh();
}).then(function () {
// UserProfile is refreshed, redirect user somewhere
$state.go("home");
});
};
}])

为单个路由定义自定义行为的最直接方法非常简单:

1)routes.js:为任何所需的路线创建一个新属性(如requireAuth)

angular.module('yourApp').config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'templates/home.html',
requireAuth: true // our custom property
})
.when('/login', {
templateUrl: 'templates/login.html',
})
.otherwise({
redirectTo: '/home'
});
})

2)在未绑定到ng-view内元素的顶层控制器中(以避免与角度$routeProvider冲突),检查newUrl是否具有requireAuth属性并采取相应的行动

angular.module('YourApp').controller('YourController', function ($scope, $location, session) {

// intercept the route change event
$scope.$on('$routeChangeStart', function (angularEvent, newUrl) {

// check if the custom property exist
if (newUrl.requireAuth && !session.user) {

// user isn’t authenticated
$location.path("/login");
}
});
});

几个月前我写了一篇关于如何使用 Angular 设置用户注册和登录功能的文章,您可以在 http://jasonwatmore.com/post/2015/03/10/AngularJS-User-Registration-and-Login-Example.aspx 查看

我检查用户是否登录了$locationChangeStart事件,这是我的主要应用程序.js显示以下内容:

(function () {
    'use strict';
 
    angular
        .module('app', ['ngRoute', 'ngCookies'])
        .config(config)
        .run(run);
 
    config.$inject = ['$routeProvider', '$locationProvider'];
    function config($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                controller: 'HomeController',
                templateUrl: 'home/home.view.html',
                controllerAs: 'vm'
            })
 
            .when('/login', {
                controller: 'LoginController',
                templateUrl: 'login/login.view.html',
                controllerAs: 'vm'
            })
 
            .when('/register', {
                controller: 'RegisterController',
                templateUrl: 'register/register.view.html',
                controllerAs: 'vm'
            })
 
            .otherwise({ redirectTo: '/login' });
    }
 
    run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];
    function run($rootScope, $location, $cookieStore, $http) {
        // keep user logged in after page refresh
        $rootScope.globals = $cookieStore.get('globals') || {};
        if ($rootScope.globals.currentUser) {
            $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
        }
 
        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            // redirect to login page if not logged in and trying to access a restricted page
            var restrictedPage = $.inArray($location.path(), ['/login', '/register']) === -1;
            var loggedIn = $rootScope.globals.currentUser;
            if (restrictedPage && !loggedIn) {
                $location.path('/login');
            }
        });
    }
 
})();

我觉得这种方式是最容易的,但也许这只是个人喜好。

当您指定登录路由(以及任何其他匿名路由;例如:/register、/logout、/refreshToken 等)时,请添加:

allowAnonymous: true

所以,像这样:

$stateProvider.state('login', {
url: '/login',
allowAnonymous: true, //if you move this, don't forget to update
//variable path in the force-page check.
views: {
root: {
templateUrl: "app/auth/login/login.html",
controller: 'LoginCtrl'
}
}
//Any other config
}

您永远不需要在检查中指定"allowAnonymous:false",如果不存在,则假定为false。在大多数 URL 都经过强制身份验证的应用中,工作量较少。而且更安全;如果您忘记将其添加到新 URL,可能发生的最坏情况是匿名 URL 受到保护。如果您以另一种方式执行此操作,指定"requireAuthentication: true",并且忘记将其添加到 URL,则会将敏感页面泄露给公众。

然后在您认为最适合您的代码设计的任何位置运行它。

//I put it right after the main app module config. I.e. This thing:
angular.module('app', [ /* your dependencies*/ ])
.config(function (/* you injections */) { /* your config */ })
//Make sure there's no ';' ending the previous line. We're chaining. (or just use a variable)
//
//Then force the logon page
.run(function ($rootScope, $state, $location, User /* My custom session obj */) {
$rootScope.$on('$stateChangeStart', function(event, newState) {
if (!User.authenticated && newState.allowAnonymous != true) {
//Don't use: $state.go('login');
//Apparently you can't set the $state while in a $state event.
//It doesn't work properly. So we use the other way.
$location.path("/login");
}
});
});

app.js

'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
$routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
$routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
$routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
$routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
$routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});

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

}]);

app.run(function($rootScope, $location, loginService){
var routespermission=['/home'];  //route that require login
var salesnew=['/salesnew'];
var salesview=['/salesview'];
var users=['/users'];
$rootScope.$on('$routeChangeStart', function(){
if( routespermission.indexOf($location.path()) !=-1
|| salesview.indexOf($location.path()) !=-1
|| salesnew.indexOf($location.path()) !=-1
|| users.indexOf($location.path()) !=-1)
{
var connected=loginService.islogged();
connected.then(function(msg){
if(!msg.data)
{
$location.path('/login');
}
});
}
});
});

登录服务.js

'use strict';
app.factory('loginService',function($http, $location, sessionService){
return{
login:function(data,scope){
var $promise=$http.post('data/user.php',data); //send data to user.php
$promise.then(function(msg){
var uid=msg.data;
if(uid){
scope.msgtxt='Correct information';
sessionService.set('uid',uid);
$location.path('/home');
}          
else  {
scope.msgtxt='incorrect information';
$location.path('/login');
}                  
});
},
logout:function(){
sessionService.destroy('uid');
$location.path('/login');
},
islogged:function(){
var $checkSessionServer=$http.post('data/check_session.php');
return $checkSessionServer;
/*
if(sessionService.get('user')) return true;
else return false;
*/
}
}
});

会话服务.js

'use strict';
app.factory('sessionService', ['$http', function($http){
return{
set:function(key,value){
return sessionStorage.setItem(key,value);
},
get:function(key){
return sessionStorage.getItem(key);
},
destroy:function(key){
$http.post('data/destroy_session.php');
return sessionStorage.removeItem(key);
}
};
}])

登录按Ctrl.js

'use strict';
app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
$scope.msgtxt='';
$scope.login=function(data){
loginService.login(data,$scope); //call login service
};
}]);

您可以使用resolve

angular.module('app',[])
.config(function($routeProvider)
{
$routeProvider
.when('/', {
templateUrl  : 'app/views/login.html',
controller   : 'YourController',
controllerAs : 'Your',
resolve: {
factory : checkLoginRedirect
}
})
}

并且,解析的功能:

function checkLoginRedirect($location){
var user = firebase.auth().currentUser;
if (user) {
// User is signed in.
if ($location.path() == "/"){
$location.path('dash'); 
}
return true;
}else{
// No user is signed in.
$location.path('/');
return false;
}   
}

Firebase 也有一种方法可以帮助您安装观察器,我建议将其安装在.run中:

.run(function(){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
console.log('User is signed in.');
} else {
console.log('No user is signed in.');
}
});
}

例如,一个应用程序有两个用户,分别称为ap和auc。我正在向每个路由传递一个额外的属性,并根据我在$routeChangeStart中获得的数据处理路由。

试试这个:

angular.module("app").config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/ap', {
templateUrl: 'template1.html',
controller: 'template1',
isAp: 'ap',
}).
when('/auc', {
templateUrl: 'template2.html',
controller: 'template2',
isAp: 'common',
}).
when('/ic', {
templateUrl: 'template3.html',
controller: 'template3',
isAp: 'auc',
}).
when('/mup', {
templateUrl: 'template4.html',
controller: 'template4',
isAp: 'ap',
}).
when('/mnu', {
templateUrl: 'template5.html',
controller: 'template5',
isAp: 'common',
}).                               
otherwise({
redirectTo: '/ap',
});
}]);

应用.js:

.run(['$rootScope', '$location', function ($rootScope, $location) {                
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (next.$$route.isAp != 'common') {
if ($rootScope.userTypeGlobal == 1) {
if (next.$$route.isAp != 'ap') {
$location.path("/ap");
}
}
else {
if (next.$$route.isAp != 'auc') {
$location.path("/auc");
}                        
}
}
});
}]);

所有人都提出了很大的解决方案,为什么您担心客户端的会话。 我的意思是当状态/url 更改时,我想您正在执行 ajax 调用以加载 tempelate 的数据。

Note :- To Save user's data you may use `resolve` feature of `ui-router`.
Check cookie if it exist load template , if even cookies doesn't exist than 
there is no chance of logged in , simply redirect to login template/page.

现在,ajax 数据由服务器使用任何 API 返回。现在重点开始发挥作用,根据用户的登录状态使用服务器返回标准返回类型。检查这些返回代码并在控制器中处理您的请求。 注意:- 对于不需要本机 ajax 调用的控制器,您可以像这样调用对服务器的空白请求server.location/api/checkSession.php这是checkSession.php

<?php/ANY_LANGUAGE
session_start();//You may use your language specific function if required
if(isset($_SESSION["logged_in"])){
set_header("200 OK");//this is not right syntax , it is just to hint
}
else{
set_header("-1 NOT LOGGED_IN");//you may set any code but compare that same       
//code on client side to check if user is logged in or not.
}
//thanks.....

在控制器内部的客户端或通过其他答案中所示的任何服务

$http.get(dataUrl)
.success(function (data){
$scope.templateData = data;
})
.error(function (error, status){
$scope.data.error = { message: error, status: status};
console.log($scope.data.error.status);
if(status == CODE_CONFIGURED_ON_SERVER_SIDE_FOR_NON_LOGGED_IN){
//redirect to login
});

注意:- 我明天或将来会更新更多

您应该在两个主要站点中检查用户身份验证。

  • 当用户更改状态时,使用'$routeChangeStart'回调进行检查
  • 当使用拦截器从 angular 发送$http请求时。

相关内容

  • 没有找到相关文章

最新更新