MyPersistentTokenRepositoryImpl使我们实现PersistentTokenRepository接口:
@Service public class MyPersistentTokenRepositoryImpl implements PersistentTokenRepository { @Autowired private JPAPersistentTokenRepository repository; @Override public void createNewToken(PersistentRememberMeToken persistentRememberMeToken) { MyPersistentToken myPersistentToken = new MyPersistentToken(); myPersistentToken.setSeries(persistentRememberMeToken.getSeries()); myPersistentToken.setUsername(persistentRememberMeToken.getUsername()); myPersistentToken.setTokenValue(persistentRememberMeToken.getTokenValue()); myPersistentToken.setUser_last(persistentRememberMeToken.getDate()); repository.save(myPersistentToken); } @Override public void updateToken(String series, String tokenValue, Date lastUsed) { MyPersistentToken myPersistentToken = repository.findBySeries(series); myPersistentToken.setUser_last(lastUsed); myPersistentToken.setTokenValue(tokenValue); repository.save(myPersistentToken); } @Override public PersistentRememberMeToken getTokenForSeries(String series) { MyPersistentToken myPersistentToken = repository.findBySeries(series); PersistentRememberMeToken persistentRememberMeToken = new PersistentRememberMeToken(myPersistentToken.getUsername(), myPersistentToken.getSeries(), myPersistentToken.getTokenValue(), myPersistentToken.getUser_last()); return persistentRememberMeToken; } @Override @Transactional public void removeUserTokens(String username) { repository.deleteByUsername(username); } } public interface JPAPersistentTokenRepository extends JpaRepository<MyPersistentToken,Long> { MyPersistentToken findBySeries(String series); void deleteByUsername(String username); } @Entity @Table(name = "persistent_token") public class MyPersistentToken { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Long id; private String username; @Column(unique = true) private String series; private String tokenValue; private Date user_last; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSeries() { return series; } public void setSeries(String series) { this.series = series; } public String getTokenValue() { return tokenValue; } public void setTokenValue(String tokenValue) { this.tokenValue = tokenValue; } public Date getUser_last() { return user_last; } public void setUser_last(Date user_last) { this.user_last = user_last; } }当自动登录认证时,Spring Security 通过series获取用户名、token以及上一次自动登录时间三个信息,通过用户名确认该令牌的身份,通过对比 token 获知该令牌是否有效,通过上一次自动登录时间获知该令牌是否已过期,并在完整校验通过之后生成新的token。