我已经使用Spring Security开发了一个注册和登录模块。我现在关注的是如何拦截自动存储的登录以在数据库中保存信息。我的意思是,当用户标记“记住我”时,如果进入我的应用程序,则会自动进入登录主页,但我想在数据库中注册该访问权。
现在,当用户明确通过登录页面时,很容易做到,但在上述情况下则不行。
此致
更新:我提供了一些额外信息:
security.xml文件
<http auto-config="true">
<form-login login-page="/login" login-processing-url="/j_spring_security_check" default-target-url="/private/dashboard" />
<remember-me key="rememberMeKey" user-service-ref="userServiceImpl" />
</http>
<authentication-manager alias="authenticationManager" />
<authentication-manager>
<authentication-provider user-service-ref="userServiceImpl">
<password-encoder hash="md5"/>
</authentication-provider>
</authentication-manager>
userServiceImpl
@Service
@Transactional
public class UserServiceImpl implements UserDetailsService {
@Resource
private UserDao userDao;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
String password = userDao.getUserPassword(username);
if (password!=null) {
userDao.registerAccess(username);
AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_REGISTERED"));
return new User(username,password, AUTHORITIES);
} else {
throw new UsernameNotFoundException("User not found: " + username);
}
}
}
答案 0 :(得分:1)
你可以做这样的事情
@Component
public class AppListener implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof InteractiveAuthenticationSuccessEvent) {
handleLoginEvent();
} else if (event instanceof HttpSessionDestroyedEvent)
handleLogoutEvent((HttpSessionDestroyedEvent) event);
}
private void handleLoginEvent() {
// handle login event
}
private synchronized void handleLogoutEvent(HttpSessionDestroyedEvent event) {
// handle logout event
}
}
此致
EDIT
将此添加到web.xml
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
答案 1 :(得分:1)
这里有多个选项:
AuthenticationSuccessHandler 对您的案件同样 (正常登录并记住我):
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
// log authentication success here for both cases
super.onAuthenticationSuccess(request, response, authentication);
}
}
在 security.xml :
中<bean id="customAuthenticationSuccessHandler" class="com.domain.security.CustomAuthenticationSuccessHandler"/>
<security:http ... >
...
<security:form-login login-page='/login.html' authentication-success-handler-ref="customAuthenticationSuccessHandler" />
<security:remember-me authentication-success-handler-ref="customAuthenticationSuccessHandler" />
</security:http>