spring security 用JPA进行安全管理中使用自定义的UserDetails时,maximumSessions()无法限制Session数
这是我自定义的UserDetails,这个user对象会保存到数据库。
//自定义的User
@Entity(name = "t_user")
public class User implements UserDetails, CredentialsContainer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
//...其他字段
}
而ConcurrentSessionControlAuthenticationStrategy#onAuthentication在执行sessionRegistry.getAllSessions方法时会到sessionRegistry的一个Map中去获取当前用户的所有session。Map.get的key是这个Principal,也就是User对象实例,之前我没有重写User的hascode和equals方法,(Map.get方法是根据hashcode获取value的,而未重写hascode,默认使用父类Object的hashcode方法,Object#hashcode相当于返回对象的内存地址),所以取出来的sessions是空集合,系统认为该用户没有在其他地方登录过。
//ConcurrentSessionControlAuthenticationStrategy#onAuthentication
public void onAuthentication(Authentication authentication, HttpServletRequest request,
HttpServletResponse response) {
List<SessionInformation> sessions = this.sessionRegistry.getAllSessions(authentication.getPrincipal(), false);
int sessionCount = sessions.size();
int allowedSessions = getMaximumSessionsForThisUser(authentication);
if (sessionCount < allowedSessions) {
// They haven't got too many login sessions running at present
return;
}
}
另外要注意,重写User的hascode和equals只需要判断username字段即可,因为用户密码和id都可能变化,但在这些变化后我们仍认为它是同一个用户。可以参考spring security自带的org.springframework.security.core.userdetails.User的这两个方法
//org.springframework.security.core.userdetails.User
public class User implements UserDetails, CredentialsContainer {
/**
* Returns {@code true} if the supplied object is a {@code User} instance with the
* same {@code username} value.
* <p>
* In other words, the objects are equal if they have the same username, representing
* the same principal.
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof User) {
return this.username.equals(((User) obj).username);
}
return false;
}
/**
* Returns the hashcode of the {@code username}.
*/
@Override
public int hashCode() {
return this.username.hashCode();
}
}