要保存用户最近登录的Spring Security,可以使用以下解决方法:
@Entity
@Table(name = "user_login_history")
public class UserLoginHistory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "login_time")
private LocalDateTime loginTime;
@Column(name = "ip_address")
private String ipAddress;
// Getters and Setters
}
使用JPA或其他ORM框架,可以在用户登录成功后保存登录历史记录。
@Component
public class UserLoginHistoryCache {
private final Cache cache;
public UserLoginHistoryCache() {
cache = CacheBuilder.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.build();
}
public UserLoginHistory get(Long userId) {
return cache.getIfPresent(userId);
}
public void put(Long userId, UserLoginHistory loginHistory) {
cache.put(userId, loginHistory);
}
public void update(Long userId, UserLoginHistory loginHistory) {
cache.put(userId, loginHistory);
}
}
在用户登录成功后,可以使用上述缓存类保存登录历史记录。
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private final UserLoginHistoryRepository loginHistoryRepository;
public CustomAuthenticationSuccessHandler(UserLoginHistoryRepository loginHistoryRepository) {
this.loginHistoryRepository = loginHistoryRepository;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// 获取用户ID、登录时间和IP地址
Long userId = ((UserDetails) authentication.getPrincipal()).getId();
LocalDateTime loginTime = LocalDateTime.now();
String ipAddress = request.getRemoteAddr();
// 保存登录历史记录到数据库
UserLoginHistory loginHistory = new UserLoginHistory(userId, loginTime, ipAddress);
loginHistoryRepository.save(loginHistory);
// 或者保存登录历史记录到缓存
// ...
}
}
在Spring Security的配置类中,使用自定义的AuthenticationSuccessHandler。
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final CustomAuthenticationSuccessHandler authenticationSuccessHandler;
public SecurityConfig(CustomAuthenticationSuccessHandler authenticationSuccessHandler) {
this.authenticationSuccessHandler = authenticationSuccessHandler;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// 配置URL权限
.anyRequest().authenticated()
.and()
.formLogin()
.successHandler(authenticationSuccessHandler);
}
}
以上是保存用户最近登录的Spring Security的几种解决方法,可以根据实际需求选择适合的方式。