springbootSecurity自定义登录
个人理解哈,springbootSecurity自定义的登陆页面,首先要实现security的基本配置,
然后,对密码进行加密
紧接着,要对用户进行认证,对特定的Authentication进行认正
再然后,用configure(AuthenticationManagerBuilder)来使AuthenticationProvider容易地添加来建立认证机制,也就是说用来记录账号,密码,角色信息
之后实现UserDetailsService接口,但是实现这个接口后我们会发现其返回参数是UserDetails类型,这就需要我们去实现改接口,并将账号密码相关的实体类放进去,
package hkyxg.education.entity;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import java.util.List;
import java.util.stream.Collectors;
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class LoginUser implements UserDetails {
private User user;
//存储权限信息
private List<String> permissions;
public LoginUser(User user, List<String> permissions) {
this.user = user;
this.permissions = permissions;
}
//存储SpringSecurity所需要的权限信息的集合
@JSONField(serialize = false)
private List<SimpleGrantedAuthority> authorities;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
if (authorities != null) {
return authorities;
}
//把permissions中String类型的权限信息封装成SimpleGrantedAuthority对象
authorities = new ArrayList<>();
for (String permission : permissions) {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
authorities.add(authority);
}
return authorities;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUserName();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
然后就可以去实现UserDetailsService接口定义方法,从数据库中获取信息进行登录,之后返回给security
在登录接口的impl层,我们用
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, password);
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
来判断security中是否有该用户的信息来进行验证,如果没有则说明用户名或密码错误,有则通过
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
来进行获取即可。