UsernamePasswordAuthenticationToken(位于org.springframework.security.authentication包下) 通过类名可以的看出来,用户名密码方式进行认证。就是我们见的最多的认证方式通过用户名密码进行登录。咱们话不多说看看具体实现:
public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {
// 序列化id
private static final long serialVersionUID = 530L;
// 一般指的是用户名
private final Object principal;
// 一般指的是密码
private Object credentials;
// 构造器
// principal 一般指的是用户名
// credentials 一般指的是密码
public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
// 初始化父类构造 权限集合为空
super((Collection)null);
this.principal = principal;
this.credentials = credentials;
// 设置是否已认证 默认为false
this.setAuthenticated(false);
}
// 构造器
// principal 一般指的是用户名
// credentials 一般指的是密码
// authorities 权限
public UsernamePasswordAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
// // 初始化父类构造 权限集合
super(authorities);
this.principal = principal;
this.credentials = credentials;
// 设置父类方法表示已经认证
super.setAuthenticated(true);
}
// 获取密码
public Object getCredentials() {
return this.credentials;
}
// 获取用户名
public Object getPrincipal() {
return this.principal;
}
// 设置是否已认证 默认为false
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
// 如果为true
// 抛出非法参数异常
if (isAuthenticated) {
throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
} else {
// 设置父类是否已认证
super.setAuthenticated(false);
}
}
// 擦除凭证
public void eraseCredentials() {
// 调用父类方法
super.eraseCredentials();
// 将密码设置为空
this.credentials = null;
}
}