一般使用SpringSecurity 都需要使用自带的url("j_spring_security_check")进行登录,但是如果你想要使用ajax登录设置就会很麻烦,但是其实可以自己实现登录的action(struts),原理也就是把认证的对象放到spring security context 中,关键代码如下:
try {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
Authentication auth = getAuthenticationManager().authenticate(token);
auth = new UserSessionAuthentication(auth, (UserSession)auth.getPrincipal());
SecurityContextHolder.getContext().setAuthentication(auth);
}catch (AuthenticationException ae) {
throw new AccessDeniedException("wrong username or password !");
}
其中UserSession是UserDetails的实现,一旦登录完成用户的权限就会缓存在内存中,所以如果想要动态地改变用户的权限的话就得在实现UserDetails中的getAuthorities()方法时从数据库中取出用户的权限而不是从用户的对象方法中取得,代码如下:
@Override
@Transactional(rollbackFor=java.lang.Exception.class,propagation = Propagation.REQUIRED)
public Collection<GrantedAuthority> getAuthorities() {
List<GrantedAuthority> out = new ArrayList<GrantedAuthority>();
out.addAll(...(user roles/rights from database));
...
}