我发现如何在前端管理我的身份验证角色时遇到了一些麻烦。我想访问身份验证角色并将其传递给根范围,但它会返回一个数组。
我想知道用户为每个角色添加了一些特权的角色。 怎么可以这样做?
如果我呼叫用户/用户
{"details":{"remoteAddress":"0:0:0:0:0:0:0:1","sessionId":"1F64CC142A715A53FFF4A9329E6B933D"},"authorities":[{"authority":"USER_ROLE"}],"authenticated":true,"principal":{"password":null,"username":"1@1","authorities":[{"authority":"USER_ROLE"}],"accountNonExpired":true,"accountNonLocked":true,"credentialsNonExpired":true,"enabled":true},"credentials":null,"name":"1@1"}
这是我的登录控制器:
(function () {
'use strict';
angular
.module('app')
.controller('LoginController', LoginController);
LoginController.$inject = ['$rootScope', '$scope', '$http', '$location', '$route','$localStorage'];
function LoginController($rootScope, $scope, $http, $location, $route,$localStorage) {
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
};
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user/', {
headers : headers
}).success(function(data) {
if (data.name) {
//This returns an array...
console.log(data.authorities);
console.log("Good Credentials");
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback($rootScope.authenticated);
}).error(function() {
$rootScope.authenticated = false;
callback && callback(false);
});
};
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function(authenticated) {
if (authenticated) {
console.log("Login succeeded");
console.log($scope.credentials.username);
$location.path("/app/dashboard");
$scope.error = false;
$rootScope.authenticated = true;
//Here we add all the variables we need to the session that are safe to be seen
//In the future we can replace this and load this in the splash screen every time the application loads so we are sure the
// variables are stored
} else {
console.log("Login failed")
$location.path("/login");
$scope.error = true;
$rootScope.authenticated = false;
}
})
};
//Logout
$scope.logout = function() {
$http.post('logout', {}).success(function() {
$rootScope.authenticated = false;
$location.path("/");
}).error(function(data) {
$location.path("/");
console.log("Logout failed")
$rootScope.authenticated = false;
});
}
}
})();
这是我的控制器
@RequestMapping("/user")
public Principal user(@AuthenticationPrincipal Principal user) {
return user;
}
答案 0 :(得分:1)
如Spring文档中所述,@AuthenticationPrincipal会将值返回给Authentication.getPrincipal()
。但是,如果查看Authentication,您将看到使用Authentication.getAuthorities()
与主体分开访问用户的权限。
您可以执行以下操作:修改自定义Principal
以包含用户的角色,或者除了控制器中的主体之外,您还可以获取权限并对其进行序列化。
您可以通过以下方式获取当前身份验证:SecurityContextHolder.getContext().getAuthentication();