AngularJS/Spring MVC, HttpSession not persistent



我们正在开发一个Web应用程序,我们正在使用Spring MVC(以及Spring BootSpring Security)和AngularJS。因此,我们为应用程序运行了两个不同的服务器。

我们

试图存储用户会话后端,以确保适当的安全级别,因此我们尝试使用 HttpSession 对象,但每次我们想要检索现有会话时,都会创建一个新实例(我们已经检查了会话 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部分?

任何帮助将不胜感激,

提前致谢

我们找到了解决方案,我们只需要在我们的应用程序中添加一些配置行.js 文件:

$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;

更多信息在这里 : 链接

希望有一天它能帮助某人!

最新更新