在我的Spring Security应用程序中,我尝试在成功登录后返回cookie“remember_token”。我的 AuthenticanSuccessHandler 类自动连接 RememberMeService 类,以从数据库中获取“令牌”值。但自动连接的引用 rememberMeService 返回null。我确实提到了类的 @Component 注释,但它没有改变结果。 Link to complete source code
FormAuthenticationSuccessHandler :
package com.fastcheck.timesheet.common.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import com.fastcheck.timesheet.common.services.RememberMeService;
@Component
public class FormAuthenticationSuccessHandler implements AuthenticationSuccessHandler
{
@Autowired
public RememberMeService rememberMeService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException
{
String username;
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails)
{
username = ((UserDetails)principal).getUsername();
}
else
{
username = principal.toString();
}
System.out.println("rememberMeService :"+rememberMeService);
if(rememberMeService != null)
{
Cookie cookie=new Cookie("remember_token",rememberMeService.getRememberMeToken(username));
cookie.setMaxAge(200);
response.addCookie(cookie);
}
response.setStatus(200);
response.sendRedirect("home");
}
}
答案 0 :(得分:3)
我从您的代码中了解到,您正在努力实现创建弹簧安全性以便为您开箱即用。
如果您正确实施了弹簧安全措施,我不明白为什么在您成功进行身份验证后,记住我的令牌不会自动存储在用户的浏览器中。
答案 1 :(得分:0)
记住令牌自动发送到浏览器。您无需单独发送。是否可以提供浏览器返回的cookie值?否则请使用下面的脚本对其进行解码。
String cookieAsPlainText = new String(Base64.decode(cookies[i].getValue());
cookieAsPlainText 作为普通值应为 series:token 格式。如果有帮助,请告诉我