前后端分离项目springsecurity实现用户登录认证快速使用
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
// 假设这是一个从数据库加载的用户实体类
public class CustomUserDetails implements UserDetails {
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
// 构造函数,从数据库加载用户信息
public CustomUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) {
this.username = username;
this.password = password;
this.authorities = authorities;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities; // 返回用户的权限集合
}
@Override
public String getPassword() {
return password; // 返回用户的密码
}
@Override
public String getUsername() {
return username; // 返回用户的用户名
}
@Override
public boolean isAccountNonExpired() {
return true; // 账户没有过期
}
@Override
public boolean isAccountNonLocked() {
return true; // 账户没有锁定
}
@Override
public boolean isCredentialsNonExpired() {
return true; // 凭证(密码)没有过期
}
@Override
public boolean isEnabled() {
return true; // 账户启用
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomUserDetails that = (CustomUserDetails) o;
return Objects.equals(username, that.username);
}
@Override
public int hashCode() {
return Objects.hash(username);
}
}
// SecurityConfig.java 的一部分
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
// SecurityConfig.java 的一部分
@Bean
public UserDetailsService userDetailsService() {
return username -> {
// 从数据库加载用户信息,这里假设已经有方法getUserDetailsFromDatabase(String username)
UserDetails userDetails = getU
评论已关闭