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