single page application deep linking with login page

前端 未结 2 1878
南笙
南笙 2021-01-14 05:11

My team is going to build a single-page-application for our future project. At the moment, I have a problem with designing the app with login page. There are 2 approaches:

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 05:43

    I decided to go with approach 2: The app has only 1 page and the login page will be a view in the app which is switched back and forth using javascript.. I found out that it's not difficult to do and I can still use normal cookie-based authentication with session on server, redirect users to default page (main page) after successful login, and so on. Here is a sample code how I do it with angularjs.

    Routing:

    var App = angular.module('App', ["ui.state"]);
    
    App.config(function ($stateProvider, $routeProvider) {
       $stateProvider.
       .state('login', {
            url: "/login?returnUrl",
            templateUrl: '/Home/Login',
            controller:"LoginController"
        })
        .state('main', {
            url: "/main",
            abstract:true,
            templateUrl: '/Home/Main',
            controller: "MainController"
         })
    })
    .run(function ($rootScope, $state, $stateParams, $location) {
         $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){ 
            if (error.status == 401) {
                $state.transitionTo("login", { returnUrl: $location.url() });
            }
         })
    });
    

    The point here is when there is a route change error with status 401 (from the server) indicating that the user is not logged in, I will transition to login state with the return url.

    After the user successfully logging in using ajax, I will transition the state back to my main view. Something like this:

    $http.post("/Login", JSON.stringify({UserName:username,Password:password}))
         .success(function (data, status, headers, config) {
            var returnUrl = $stateParams.returnUrl ? $stateParams.returnUrl : "mydefaulturl";
            $location.url(returnUrl);
     })
    

    With this approach, now I'm able to create deep-link to jump to a specific state in my app with login page and return url.

提交回复
热议问题