2016-11-02 8 views
1

次のコントローラ/サービスをAngularjsに組み込み、認証サービスに連絡します。私はこれを利用して、Angularアプリケーションの他のページをこのサービスで認証されたユーザーに制限したいと思いますが、その方法はわかりません。私は誰かが正しい方向に私を向けることを望んでいる。以下は私のコントローラとサービスです。認証されたユーザーへのアクセスを制限するにはどうすればよいですか?

angular.module('App').controller('LoginController', function ($scope, $rootScope, $window, AuthenticationService) { 

//function that gets called when the form is submitted. 
$scope.submit = function() { 
    var promise = AuthenticationService.login($scope.user, $scope.password); 

    promise.then(function() { 
     var success = AuthenticationService.isAuthenticated(); 
     if (success === true) { 
      $window.location.href = "/welcome.html"; 
     } 
    }); 
} 
}); 

app.service('AuthenticationService', function ($http) { 
//Used to track if the user was able to successfully authenticate. 
var auth = false; 
var token = undefined; 

//Had to put this in because I am running into weird behavior when attempting to retrieve a value from response.headers('value');. 
//When assiging this to a var, it would always come out as a null value. If you send the value into a function without assigning 
//it to a var, the value would be there as expected. For instance, console.log(response.headers('Authorization')); would work, but 
//token = response.headers('A‌​uthorization'); would result in a null value. The function below is a workaround. 
var getResponseHeader = function (x) { return x; } 

//Makes a call to the WEB API Authentication service with the username/password and attempts to authenticate. 
var login = function (user, pass) { 
    var input = { UserName: user, Password: pass }; 

    return $http({ 
     url: "/api/Authentication/Login/{credentials}", 
     method: "POST", 
     data: JSON.stringify(input), 
     dataType: "json" 
    }).then(function (response) { 
     if (response.status === 200) { //Call to the service was successful. 

      //This makes no sense. See comment for getResponseHeader function. 
      token = getResponseHeader(response.headers('Authorization')); 

      //If the authentication was successful, 'token' will have a value. If it was not successful, it will be null. 
      if (token) { 
       auth = true; 
      } 
     } 
     //There was an error when attempting to authenticate. Alert(response) is there for debugging purposes. 
     //This will be replaced with a user-friendly error message when completed. 
    }, function (response) { 
     alert(response); 
    }); 
} 

//Logs the user out by removing the token and setting auth back to false 
var logout = function (sessionid) { 
    auth = false; 
    token = undefined; 
} 

//Accessor for the 'auth' variable. 
var isAuthenticated = function() { return auth; } 

//Accessor for the token. 
var getToken = function() { return token; } 

return { 
    login: login, 
    logout: logout, 
    isAuthenticated: isAuthenticated, 
    token: getToken 
}; 
}); 

サービス/コントローラは認証されますが、誰でもアプリケーションの「welcome.html」や他のページを参照できます。これを認証に成功したユーザーに限定するにはどうすればよいですか?

+0

必要なお知らせ:ブラウザ全体でJavascriptアプリケーションが実行されているため、特定のページやデータに対してサーバー側のコントロールを使用せずにJavascript Webサイトのコンテンツを秘密にする* * *ソリューションはありません。認証されているかどうかにかかわらず、クライアントはコードを読み取り、アプリケーションの状態を変更できます。アクセスを制限せずにインターフェース(検出/ログイン/ログアウト)を単純に改善するには、以下のソリューションを使用してください。 –

答えて

0

私はあなたがそうのようなあなたの状態を設定angular-permissions

使用することをお勧めします:ルートアプリケーションのjsファイルで

//A Group for not logged in users 
.run(function(PermPermissionStore) { 
    PermPermissionStore 
    .definePermission('anonymous', function() { 
     // Do your authentification here 
     // you can sett up your funtions elsewere and call them here 
     // return true if unauthorized 
     var auth = auth_function() 
     if (auth === true) { 
     return false 
     } else { return true } 
    }) 
}) 

//group for authentificated users 
.run(function(PermPermissionStore) { 
PermPermissionStore 
    .definePermission('isAuthorized', function() { 
     // Do your authentification here 
     // return true if authorized 
     var auth = auth_function() 
     if (auth === true) { 
     return true 
     } else { return false } 
    }) 
}) 
0

:真偽のための2つのグループを

.state('home', { 
     url: '/', 
     templateUrl: 'templates/home.html', 
     parent: 'parent', 
     data: { 
      permissions: { //section for permissions 
      only: 'isAuthorized', // only allow loged in users 
      redirectTo: 'login' // if not allowed redirect to login page 
      } 
     }, 
     }) 

.state('login', { 
     url: '/login', 
     templateUrl: 'templates/login.html', 
     parent: 'login-parent', 
     data: { 
      permissions: { 
      only: 'anonymous', 
      redirectTo: 'home' 
      } 
     } 
     }) 

と設定runメソッドが認証値を確認し、認証されていない場合はリダイレクトするため、app.jsのrunメソッドはこの時計を設定するのに適しています:

SEE FIDDLE EXAMPLE OF YOUR CODE

.run(['AuthenticationService', '$location', '$rootScope', function (AuthenticationService, $location, $rootScope) { 

      $rootScope.$watch(function() { 
       if (!AuthenticationService.isAuthenticated()) 
        $location.path("/login"); 

       return $location.path(); 
      }); 


     }]) 

このシンプルな時計は、あなたが何unauthed、ユーザーが任意のページにアクセスできなくなります確信できるので、あなたは別の条件を追加することにより、ロジックを変更する必要があり、AuthenticationServiceであなたにisAuthenticatedメソッドを呼び出すことにより、認証値をチェックします指定されたページへのアクセスを制限するようにルートをチェックします。

+0

私は何かが欠けているに違いありません。このコードは、最初のログインページに移動するとヒットしますが、/SomePageThatRequiresAuth.htmlを参照すると、コードがヒットせず、ユーザーが認証されていなくてもページが読み込まれます。 – Dave

+0

AuthenticationServiceがrunメソッドに正常に挿入されているように見えません。何か案は? – Dave

+0

エラーなし、空白の画面が表示されます。 – Dave

関連する問題