2017-08-09 269 views
0

我對Java Web編程非常陌生,我試圖編寫一種方法來驗證用戶身份,將一個令牌存儲在cookie中,並將它們傳遞到下一頁。我掛了認證的返回類型應該是什麼。它是否應該直接返回一個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 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://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; 
} 
+0

你是什麼意思餅乾的返回類型是什麼?這就像說「數據庫的返回類型是什麼」 - 一個cookie只是一個客戶端存儲機制。 – EJoshuaS

回答

0

你似乎是使用澤西作爲後端的框架,所以你需要看他們的文檔,看看如何設置cookie的工作原理。不,你可能無法返回純粹的cookie,因爲瀏覽器不會理解它,特別是因爲你正在「生產」JSON。

How to set cookie in Jersey

正如你從接受的答案中看到的那樣,Response對象應該有一個單獨的設置cookie的方法,正確地命名爲cookie()

相關問題