繁体   English   中英

在不使用“路由”的情况下使用AngularJS刷新单页应用程序时如何验证登录用户?

[英]How to authenticate logged in user when refreshing single page application using AngularJS without “Routing”?

我搜索了很多资源,但没有一个适合我的问题。我正在处理single page application (SPA)项目,并且希望logged in user stay logged in刷新页面时stay logged in 无需进行 路由

我试图在页面的主controller中调用session authentication servlet (此servlet检查会话是否存在),但是它不起作用。

注意:用户log insing up便会创建会话。 这是SessionAuthServlet.java

HttpSession session = request.getSession(true);
User u=(User) session.getAttribute("usersession");
try{
    response.setContentType("application/json; charset=UTF-8");
    PrintWriter out = response.getWriter();
    if(u != null)
    {
        out.println("{\"+success+\"}");
        out.close();
    }
    else
    {
        out.println("{ \"result\": \"fail\"}"); 
        out.close();
    }
    }catch (IOException e) {  
        e.printStackTrace();  
}

HTML单页应用程序中的MainController

appvar.controller('MianController',['$scope','$http','$rootScope',function($scope, $http,$rootScope) {                      
    $rootScope.sessionvalid=function(){
        $http.get("http://localhost:8080/MyProject/SessionAuthServlet")
        .success(function(response) {
            if (response.result=="fail")
                {
                  //***Show the view for not logged user      
                }
                  //***Show the view for logged user
                }

                $rootScope.sessionvalid();
       });
    }
}]);

有什么想法如何处理吗?

请指导我

谢谢

在页面刷新后,不使用路由就可以保持登录状态。 您将需要以下三件事

  1. 一种角度服务,用于保存用户信息以及是否通过身份验证。
  2. 窗口会话存储以保存用户信息。 即使页面被刷新,用户信息也将保留在会话存储中
  3. 设置请求和响应的拦截器。

服务代码-

    app.service('AuthenticationService', function() {
        var auth = {
            isLogged: false,
            email:"",
            isAdmin:false
        } 
        return auth;
    });

在您的MainController中,一旦用户登录,请设置Service AuthenticationService.isLogged = true和$ window.sessionStorage = userInfo

拦截器代码-

    app.service('TokenInterceptor', function ($q, $window, $location, AuthenticationService) {
return {
    request: function (config) {
        config.headers = config.headers || {};
        if ($window.sessionStorage.token) {
            config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
        }
        return config;
    }, 

    /* Set Authentication.isAuthenticated to true if 200 received */
    response: function (response) {
        if (response != null && response.status == 200 && $window.sessionStorage.token && !AuthenticationService.isAuthenticated) {
            AuthenticationService.isAuthenticated = true;
        }
        return response || $q.when(response);
    }
};
});

并在您的app.config块中添加-

app.config(function($httpProvider){
  $httpProvider.interceptors.push(TokenInterceptor);
})

现在,即使页面已被引荐,您的AuthenticationService.isLogged也将保持为true,并且您可以在服务中获取登录的用户信息。

暂无
暂无

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

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