大神链接
- 新建一个有Security的项目,引入数据库等所需的依赖
- 用户表
create table if not exists `sys_user` (
`id` bigint not null auto_increment comment 'id',
`user_name` varchar(64) not null default '' comment '用户名',
`nick_name` varchar(64) not null default '' comment '昵称',
`password` varchar(255) not null default '' comment '密码',
`status` tinyint not null default 1 comment '状态 0-停用 1-正常',
`create_time` datetime default null comment '创建时间',
`update_time` datetime default null comment '更新时间',
primary key (`id`)
)engine=InnoDB default charset=utf8mb4 comment = '用户表';
核心代码实现
- 密码加密 BCryptPasswordEncoder
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder()
String crypt = bCryptPasswordEncoder.encode("123456")
@Data
public class LoginUser implements UserDetails {
private User user;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@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;
}
}
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
lambdaQueryWrapper.eq(Strings.isNotEmpty(username),User::getUserName,username);
User user = userMapper.selectOne(lambdaQueryWrapper);
if (Objects.isNull(user)) {
throw new RuntimeException("用户名未找到!");
}
LoginUser loginUser = new LoginUser();
loginUser.setUser(user);
return loginUser;
}
}
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests()
.antMatchers("/api/login").permitAll()
.anyRequest().authenticated();
return httpSecurity.build();
}
}
public interface LoginService extends IService<User> {
public GResponse login(User user);
}
@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public GResponse login(User user) {
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
Authentication authenticate = authenticationManager.authenticate(authenticationToken);
if (Objects.isNull(authenticate)) {
throw new RuntimeException("登录失败!");
}
LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
return GResponse.success("登录成功!",loginUser);
}
}
@PostMapping("/api/login")
public GResponse login(@RequestBody User user) {
return loginService.login(user);
}
