由于目前项目中使用了Spring Security 2.0.1 权限管理框架,登入成功后可能就需要处理些登录日志等等后续操作,Security 3之后只需要在form-login中添加authentication-success-handler-ref即可,一般是authentication-success-handler实现AuthenticationSuccessHandler的onAuthenticationSuccess方法。那在2.0下应该怎么做呢?
关键代码 ProviderManager 类中 在 doAuthentication 授权成功的时候,创建了授权成功事件。 触发登录成功后置业务 就是 监听该事件并做相关操作。
[java]
if (result != null) {
sessionController.registerSuccessfulAuthentication(result);
publishEvent(new AuthenticationSuccessEvent(result));
return result;
}
if (result != null) {
sessionController.registerSuccessfulAuthentication(result);
publishEvent(new AuthenticationSuccessEvent(result));
return result;
}[java] view plaincopyprint public abstract class AbstractAuthenticationEvent extends ApplicationEvent {
//~ Constructors ===================================================================================================
public AbstractAuthenticationEvent(Authentication authentication) {
super(authentication);
}
//~ Methods ========================================================================================================
/**
* Getters for the Authentication request that caused the event. Also available from
* super.getSource().
*
* @return the authentication request
*/
public Authentication getAuthentication() {
return (Authentication) super.getSource();
}
}
public abstract class AbstractAuthenticationEvent extends ApplicationEvent {
//~ Constructors ===================================================================================================
public AbstractAuthenticationEvent(Authentication authentication) {
super(authentication);
}
//~ Methods ========================================================================================================
/**
* Getters for the Authentication request that caused the event. Also available from
* super.getSource().
*
* @return the authentication request
*/
public Authentication getAuthentication() {
return (Authentication) super.getSource();
}
}
由上面源代码实现授权成功事件监听器 :
[java]
public class LoginSuccessListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof AuthenticationSuccessEvent) {
AuthenticationSuccessEvent authEvent = (AuthenticationSuccessEvent) event;
UserDetails user = (UserDetails) authEvent.getAuthentication().getPrincipal();
System.out.println("模拟输出用户登录日志:[" + java.util.Calendar.getInstance().getTime() + "] " + user.getUsername());
}
}
}
public class LoginSuccessListener implements ApplicationListener {
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof AuthenticationSuccessEvent) {
AuthenticationSuccessEvent authEvent = (AuthenticationSuccessEvent) event;
UserDetails user = (UserDetails) authEvent.getAuthentication().getPrincipal();
System.out.println("模拟输出用户登录日志:[" + java.util.Calendar.getInstance().g