注册成功后自动登录
我想要在spring成功注册后自动登录:我有一个受保护的页面,需要登录才能访问它们,我要在注册后跳过登录页面并进行自动登录,以便用户可以看到受保护的页面有我吗?我正在使用spring 3.0,spring security 3.0.2,该怎么做?
回答:
可以通过以下方式(半伪代码)通过spring安全性完成此操作:
import org.springframework.security.web.savedrequest.RequestCache;import org.springframework.security.web.savedrequest.SavedRequest;
@Controller
public class SignupController
{
@Autowired
RequestCache requestCache;
@Autowired
protected AuthenticationManager authenticationManager;
@RequestMapping(value = "/account/signup/", method = RequestMethod.POST)
public String createNewUser(@ModelAttribute("user") User user, BindingResult result, HttpServletRequest request, HttpServletResponse response) {
//After successfully Creating user
authenticateUserAndSetSession(user, request);
return "redirect:/home/";
}
private void authenticateUserAndSetSession(User user, HttpServletRequest request) {
String username = user.getUsername();
String password = user.getPassword();
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
// generate session if one doesn't exist
request.getSession();
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
}
}
更新:仅包含注册后如何创建会话
以上是 注册成功后自动登录 的全部内容, 来源链接: utcz.com/qa/433775.html