简体   繁体   中英

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

I searched a lot of resources but none was appropriate to my problem.I am working on single page application (SPA) project ,and I want a logged in user to stay logged in whenever he refreshes the page but without routing .

I have tried to call session authentication servlet in the main controller of the page(this servlet checks whether the session exists or not),but it did not work.

Note: The session is created once the user log in or sing up . Here is 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();  
}

MainController in HTML single page application:

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();
       });
    }
}]);

Any ideas how to deal with this?

Please guide me

Thanks

Here is how you can stay logged after page refresh without using routing. You will need below three things

  1. A angular service to hold user information and if he is authenticated or not.
  2. A window sessionstorage to save user information. Even if the page is refereshed the user information will persist in sessionstorage
  3. An interceptor to set request and response.

Service code -

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

In your MainController, once user is logged in set the Service AuthenticationService.isLogged = true and $window.sessionStorage = userInfo

Interceptor code-

    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);
    }
};
});

and in your app.config block add this -

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

Now your AuthenticationService.isLogged will remain true even if the page is refershed and you can get the logged in user info in the service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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