【发布时间】:2015-04-01 13:38:59
【问题描述】:
我在前端使用 AngularJS,在后端使用 Java EE。 我创建了两种使用 RESTful 服务登录和注销的方法:
@POST
@Path("login")
@Produces("application/json")
public Response login(@Context HttpServletRequest req, UserTable user) {
if (req.getUserPrincipal() == null) {
try {
req.login(user.getUsername(), user.getPassword());
} catch (ServletException e) {
return Response.status(Response.Status.BAD_REQUEST).type("text/plain").entity("Login or Password is incorrect").build();
}
} else {
return Response.status(Response.Status.OK).type("text/plain").entity("You are already logged in").build();
}
return Response.status(Response.Status.OK).type("text/plain").entity("Login successfull").build();
}
@GET
@Path("logout")
@Produces("application/json")
public Response logout(@Context HttpServletRequest req) {
try {
req.logout();
req.getSession().invalidate();
} catch (ServletException e) {
return Response.status(Response.Status.BAD_REQUEST).type("text/plain").entity("Can not logout").build();
}
return Response.status(Response.Status.OK).type("text/plain").entity("Logout successfull").build();
}
在前端,我使用这些方法:
$http.post(apiUrl + 'usertable/login', {
username: 'admin',
password: 'admin'
});
$http.get(apiUrl + 'usertable/logout').success(function (a) {
var o = a;
});
我可以成功登录:
FINEST: JDBC login succeeded for: admin groups:[Admin]
FINE: JAAS login complete.
FINE: JAAS authentication committed.
FINE: Password login succeeded for : admin
但是当我尝试注销或再次登录时,getUserPrincipal() 返回 null。我做错了什么?
【问题讨论】:
-
听起来问题出在您的服务器端。设置一些断点以查看正在采用的路径并沿途检查数据。这应该会引导您解决问题。
-
如果您在注销后再次尝试登录,getUserPrincipal 将始终为您提供 null,因为用户未通过身份验证。这就是 req.logout() 方法正在做的事情。
-
@rahpuser 我已经尝试使用登录方法并且没有注销我第二次使用它,但是第二次 getUserPrincipal() 等于 null。
-
Cookie 是否在交互过程中保存?
-
@SoluableNonagon 我已经做到了。我试图写这样的东西: Principal p = req.getUserPrincipal();在登录和注销方法中。每次 'p' 都等于 null。