除了使用J2EE preauthentication
之外,我还将身份验证管理放在自定义pojo类中:
public boolean grantAuthentication(UserRole role) {
List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
if(role.equals(UserRole.ROLE_ADMIN)){
authorities.add(new SimpleGrantedAuthority(UserRole.ROLE_ADMIN.toString()));
}
authorities.add(new SimpleGrantedAuthority(UserRole.ROLE_USER.toString()));
Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(),
authorities);
user.setAuthorities(authorities);
// here the authentication inject into SecurityContext
SecurityContextHolder.getContext().setAuthentication(authentication);
return true;
}
上面的类位于从登录页面处理用户登录表单的controller
类中。
但是如果用户进入某个东西,例如/ order / view然后重新启动应用程序,并刷新页面,则会有一个例外抱怨:
java.lang.NullPointerException: Cannot obtain authentication object in security context at this time
Cannot obtain authentication object in security context at this time
那么无论如何都要在会话中维护身份验证对象,或者我是否必须将用户重定向回登录页面?如果是这样,那么我该如何将用户带回登录页面呢?
答案 0 :(得分:0)
如果添加spring会话管理,它将自动处理。在springsecurity.xml中添加会话管理,如下所示,
<security:session-management
invalid-session-url="/jsp/general/sessionTimeout.html" />