【问题标题】:Cookie use Jaxax.servlet.http or Javax.was.rs.core?Cookie 使用 Jaxax.servlet.http 还是 Javax.was.rs.core?
【发布时间】:2018-01-18 21:35:53
【问题描述】:

我试图在身份验证后存储一个 cookie,但不知道如何调整 authenticateUser 方法以接受正确的 cookie。

@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 Response.ok(token).build();
    //https://stackoverflow.com/questions/7231156/how-to-set-cookie-in-jersey
    return Response.ok(token)
       .cookie(new NewCookie(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://stackoverflow.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 不喜欢它(找不到setSecure):

import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Response;

在这种情况下如何修复 cookie 或 authenticateUser 方法?

【问题讨论】:

    标签: java servlets cookies jax-rs


    【解决方案1】:

    如果您在 JAX-RS 中使用 ResponseBuilder,则需要使用 javax.ws.rs.core.NewCookie,它扩展了 javax.ws.rs.core.Cookie

    http://docs.oracle.com/javaee/7/api/javax/ws/rs/core/NewCookie.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      相关资源
      最近更新 更多