大家晚上好,我正在尝试解决Spring Boot的一个让我生气的问题...
我正在使用Spring Boot和AngularJS 1.5.1制作一个简单的Web应用程序(在这个阶段,细节不是根本)
我使用rest API进行了身份验证,
@PostMapping("/login")
@ResponseBody
public UserLoginResponse login(@RequestBody UserLogin userLogin, HttpServletResponse response, HttpServletRequest req) {
UserLoginResponse resp;
HttpSession currentSession = req.getSession(true);
resp = new UserLoginResponse();
logger.info(MessageFormat.format("CALLED - Login from user {0}",userLogin.getEmail()));
resp.setId(userLogicManager.login(userLogin, currentSession));
if(resp.getId() == -1) {
response.setStatus(HttpStatus.NOT_FOUND.value());
logger.info(MessageFormat.format("ERROR - Login failed user {0}",userLogin.getEmail()));
currentSession.invalidate();
}
return resp;
}
这将在此处调用其逻辑管理器:
public Long login(UserLogin userLogin, HttpSession session) {
User user;
Long res = new Long(-1), currTime;
Date loginDate;
logger.info(MessageFormat.format("LOGIC - Login user {0}", userLogin.getEmail()));
loginDate = new Date();
currTime = loginDate.getTime();
user = userRepository.findUserByEmailAndPassword(userLogin.getEmail(), hashString(userLogin.getPassword()));
if (user != null) {
user.setLastLogin(new Timestamp(currTime));
userRepository.save(user);
res = user.getId();
session.setAttribute("uid", user.getId());
logger.info(MessageFormat.format("LOGIC - COMPLETED - Login user {0}", userLogin.getEmail()));
}
return res;
}
我以这种方式发出请求:
let loginUrl = mainConst.API_PROXY_URL;
let apiUrl = mainConst.API_BASE_URL + "user/login";
let requestParams = {
method: "POST",
url: loginUrl,
data: credentials,
headers : {
'Target-URL': apiUrl,
'Authorization': ""
},
withCredentials: true
};
$http(requestParams).then(success, fail);
我正在通过一个nodejs代理来处理CORS,并添加了这些标头
res.header(“ Access-Control-Allow-Origin”,“ http://localhost”); res.header(“ Access-Control-Allow-Methods”,“ GET,PUT,PATCH,POST,DELETE”); res.header(“ Access-Control-Allow-Headers”,req.header('access-control-request-headers')+“,Set-Cookie,Cookie”);
此呼叫后,我正确地从服务器获取了此标头:
set-cookie
SESSION = YjI5NzBjZjYtYmRiZC00Nz…jJiNzg4;路径= /; SameSite = Lax
问题
当我尝试使用此会话时,例如使用此API
@GetMapping("/restaurants")
@ResponseBody
public RestaurantResponse getRestaurants(HttpServletResponse response, HttpServletRequest req) {
HttpSession currentSession = req.getSession(false);
RestaurantResponse res = userLogicManager.getRestaurants(currentSession);
if(res == null) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
logger.info("ERROR - Get restaurant failed - Not logged performer");
}
return res;
}
currentSession始终为null,即使对此API的请求具有
饼干
SESSION = YjI5NzBjZjYtYmRiZC00NzZmLTlkY2EtMDc0ZDQxZjJiNzg4
标题。
我该怎么做才能解决此问题?我正在尝试使用HttpSession进行身份验证过程,但这阻塞了我的项目,我一周要尝试解决它