【发布时间】:2016-09-30 12:50:24
【问题描述】:
我们正在开发一个网络应用程序,我们正在使用Spring MVC(以及Spring Boot 和Spring Security)和AngularJS。
因此,我们为应用程序运行了两个不同的服务器。
我们正在尝试存储用户会话后端,以确保适当的安全级别,因此我们尝试使用HttpSessionobject,但每次我们想要检索现有会话时,都会创建一个新实例(我们'已经检查了会话 ID)。
这是我们正在做的登录:
$scope.authenticate = function () {
var postObject = new Object();
postObject.mail = $scope.userName;
postObject.password = $scope.userPassword;
$http({
url: "http://localhost:8080/login",
method: "POST",
dataType: "json",
data: postObject,
headers: {
"Content-Type": "application/json"
}
}).success(function successCallback(response, status) {
if (status == 200) {
$scope.messageAuth = "Login successful"
$scope.go('/services');
}
})
.error(function errorCallback(error, status) {
$scope.messageAuth = "Error " + response;
});
};
然后,我们检查凭据,如果它们正确,我们将用户信息存储到新会话中:
@RestController
public class UserController {
@Resource
UserService userService;
@CrossOrigin
@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<User> loginSubmit(@RequestBody User user, HttpServletRequest request, HttpSession session) {
if (isAuthorized(user)) {
User authenticatedUser = this.userService.getUserByMail(user.getMail());
authenticatedUser.setPassword(null);
session.invalidate();
HttpSession newSession = request.getSession(true);
newSession.setAttribute("USER_ROLE", authenticatedUser.getRole());
System.out.println("/login : SESSION ID = " + newSession.getId());
System.out.println("/login : " + newSession.getAttribute("USER_ROLE"));
return ResponseEntity.ok(authenticatedUser);
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(null);
}
}
@RequestMapping("/user")
public String user(Principal user, HttpServletRequest request, HttpSession session) {
System.out.println("/user : SESSION ID = " + session.getId());
System.out.println("/user : " + (String) request.getSession(false).getAttribute("USER_ROLE"));
return (String) session.getAttribute("USER_ROLE");
}
最后,从 Angular 应用程序中,我们希望通过调用 /user 来获取用户信息,如下所示:
var f = function() {
$http.get('http://localhost:8080/user').success(function successCallback(response) {
console.log(response);
}).error(function() {
console.log('error');
})
};
我们已经尝试了几乎所有关于如何使用 Spring Security 管理会话的方法,也许问题出在 Angular 部分?
任何帮助将不胜感激,
提前致谢
【问题讨论】:
-
您没有使用 Spring Security,您实际上是在解决它...
-
感谢您的反馈,您认为这是问题的一部分吗?无论如何,我们应该可以使用
HttpSession,对吧? -
如果您使用 Spring Security 并使用默认值
/login会被 Spring Security 拦截,并且您的控制器不会执行任何操作。应该没有什么可以阻止您使用HttpSession(我们在我当前的项目中使用了类似的设置)。 -
我尝试通过
/authent更改/login,结果相同。它似乎与 Spring Security 无关,因为当我禁用它时,问题仍然存在(仍然是HttpSession的新实例)
标签: angularjs spring spring-mvc session