Mah*_*leh 30 spring spring-security
嘿所有我想在春季成功注册后进行自动登录意味着:我有一个受保护的页面,需要登录才能访问它们,我希望在注册后跳过登录页面并进行自动登录,以便用户可以看到该受保护的页面得到了我?我使用的是spring 3.0,spring security 3.0.2怎么办?
Spr*_*key 40
这可以通过以下方式使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
更新:仅包含注册后如何创建会话
Hen*_*k T 12
在Servlet 3+中,您可以轻松完成request.login("username","password"),如果成功,则重定向到您想要的任何页面.您可以执行相同的自动注销.
以下是文档部分的链接:http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#servletapi-3
小智 8
只是对第一个回复如何自动验证authenticationManager的评论.
在applicantion-servlet.xml或applicationContext-security.xml文件中声明authentication-manager时,需要设置别名:
<authentication-manager alias="authenticationManager>
<authentication-provider>
<user-service>
<user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="bob" password="bobspassword" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Run Code Online (Sandbox Code Playgroud)
此外,当您进行身份验证时,它可能会抛出AuthenticationException,因此您需要捕获它:
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword());
request.getSession();
token.setDetails(new WebAuthenticationDetails(request));
try{
Authentication auth = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
} catch(Exception e){
e.printStackTrace();
}
return "redirect:xxxx.htm";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25727 次 |
| 最近记录: |