如何在Angular中存储用户会话? [英] How to store user session in Angular?
问题描述
我刚刚开始使用AngularJS,我试图在我的AngularApp存储用户会话。
第一步提交用户名和密码工作。
之后,我将从 $ rootScope
中检索的用户名
下一页可以显示存储的用户名
。
但是刷新后, $ rootScope
为空。
我试图做一个尽可能简单的验证系统。
myApp.controller('loginController',['$ scope','$ rootScope','$ location','AuthService ','$ route',
function($ scope,$ rootScope,$ location,AuthService,$ route){
$ scope.login = function(credentials){
AuthService.login(credentials).then(function(response){
if(response.data ==0){
alert(Identifiant ou mot de passe incorrect);
}
else {
// response.data是以下的JSON
$ rootScope.credentials = response.data;
$ location.path(/);
}
});
};
}]);
AuthService.login()
code> $ http 请求。
JSON
{user_id:1,user_name:u1,user_display_name:Steffi}
HTML:
< div>欢迎{{credentials.user_display_name}}!< / div>
我尝试了很多教程,但我不能使会话工作。
我已经使用UserApp,但它不对我确定。我想创建自己的简单身份验证。
$ rootScope
您需要使用客户端持久存在的东西,例如作为cookie或sessionStorage(因为它们都有一个到期时间)。请查看
$ cookieStore
的文档: https://docs.angularjs.org/api/ngCookies/service/$cookieStore 请记住,敏感会话信息应加密。 / p>
I have just started using AngularJS and I'm trying to store user session on my AngularApp.
First step to submit username and password works.
After that, I store the username
retrieved from the service in the $rootScope
.
The next page can display the username
stored.
But after a refresh, the $rootScope
is empty.
I'm trying to do an authentication system as simple as possible.
myApp.controller('loginController', ['$scope', '$rootScope', '$location', 'AuthService', '$route',
function ($scope, $rootScope, $location, AuthService, $route) {
$scope.login = function (credentials) {
AuthService.login(credentials).then(function (response) {
if(response.data == "0"){
alert("Identifiant ou mot de passe incorrect");
}
else {
// response.data is the JSON below
$rootScope.credentials = response.data;
$location.path("/");
}
});
};
}]);
AuthService.login()
makes a $http
request.
JSON
{user_id: 1, user_name: "u1", user_display_name: "Steffi"}
HTML :
<div>Welcome {{ credentials.user_display_name }}!</div>
I tried a lot of tutorials, but I can't make session work. I already used UserApp but it's not ok to me. I would like to create my own simple authentication.
$rootScope
will always reset when the page refreshes, since it's a single-page app.
You need to use something that persists client-side, such as a cookie or sessionStorage (as they both have an expiration time). Take a look at the documentation for $cookieStore
: https://docs.angularjs.org/api/ngCookies/service/$cookieStore
Remember, sensitive session information should be encrypted.
这篇关于如何在Angular中存储用户会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!