应用程序重启后如何在SecurityContext中维护身份验证?

时间:2014-01-21 16:01:00

标签: spring spring-mvc spring-security

除了使用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

那么无论如何都要在会话中维护身份验证对象,或者我是否必须将用户重定向回登录页面?如果是这样,那么我该如何将用户带回登录页面呢?

1 个答案:

答案 0 :(得分:0)

如果添加spring会话管理,它将自动处理。在springsecurity.xml中添加会话管理,如下所示,

<security:session-management
            invalid-session-url="/jsp/general/sessionTimeout.html" />