cookie 的返回类型是啥?
Posted
技术标签:
【中文标题】cookie 的返回类型是啥?【英文标题】:What is the return type of a cookie?cookie 的返回类型是什么? 【发布时间】:2018-01-17 23:02:10 【问题描述】:我是 Java Web 编程的新手,我正在尝试编写一种方法来验证用户,将令牌存储在 cookie 中,并将它们传递到下一页。我挂断了身份验证的返回类型应该是什么。是否应该直接返回一个Cookie对象作为authenticateUser()
的返回值?
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response authenticateUser(@FormParam("username") String username,
@FormParam("password") String password)
try
// Authenticate the user using the credentials provided
authenticate(username, password);
// Issue a token for the user
_logger.log(Level.INFO, "----ABOUT TO LOG TOKEN TO WILDFLY");
String token = issueToken(username,"http://example.com","userToken",msInHour); //returns JWT token
_logger.log(Level.INFO, "----LOGGING TOKEN TO WILDFLY: ",token);
// Return the token on the response
//return Response.ok(token).build();
Response.createCookie(createCookie(token,username)).build();
catch (Exception e)
_logger.log(Level.INFO, "----ERROR in AuthService:",e);
return Response.status(Response.Status.FORBIDDEN).build();
private Cookie createCookie(String token,String uname)
//https://***.com/questions/8889679/how-to-create-a-cookie-and-add-to-http-response-from-inside-my-service-layer
final Boolean useSecureCookie = true;
final int expiryTime = 60 * 60 * 24; // 24h in seconds
final String cookiePath = "/";
Cookie cookie = new Cookie("example.com", uname+"_"+token);
cookie.setSecure(useSecureCookie); // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
cookie.setMaxAge(expiryTime); // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
cookie.setHttpOnly(true);
cookie.setPath(cookiePath); // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories
return cookie;
【问题讨论】:
什么意思 cookie 的返回类型是什么?这就像说“数据库的返回类型是什么”——cookie 只是一种客户端存储机制。 【参考方案1】:您似乎使用 Jersey 作为后端框架,因此您需要查看他们的文档以了解设置 cookie 的工作原理。不,您很可能无法返回纯 cookie,因为浏览器不会理解它,特别是因为您正在“生产”JSON。
How to set cookie in Jersey.
从接受的答案中可以看出,Response
对象应该有一个单独的方法来设置 cookie,恰当地命名为 cookie()
。
【讨论】:
以上是关于cookie 的返回类型是啥?的主要内容,如果未能解决你的问题,请参考以下文章