spring security 使用数据库数据进行认证:
提示:security更新后还需要添加加密方式:
参考:
springboot+security 的BCryptPasswordEncoder 使用
SpringBoot Security:Encoded password does not look like BCrypt 解决
以及其狂神的视频,还有其他博主。
主要代码:
实体类:我这边用的是lombok, 不用记得加上 set,get 方法,无参构造。
里面主要得有两个字段:账号,密码,我这里是手机号,role 是身份;
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
/**
* @author Nuisance
* @since 2020-08-31
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String phone;
private String password;
private String role;
private String username;
}
mapper:mapper接口,
import com.example.demo.blog.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author Nuisance
* @since 2020-08-31
*/
public interface UserMapper extends BaseMapper<User> {
//这边写一个select方法,我用的是mybatisPlus,已经继承了父类的方法所以没写;
}
service:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.subject.LiTu.entity.User;
import com.example.subject.LiTu.mapper.UserMapper;
import com.example.subject.LiTu.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author Nuisance
* @since 2020-08-31
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {
@Autowired
private UserMapper userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("进入service,用户为 : " + username);
if(username == null || username == ""){
throw new UsernameNotFoundException("请输入用户手机号!");
}
/**
下面三行就是换成mapper写的 select方法,查询user中的账号,密码,以及身份
*/
QueryWrapper<User> wrapper =new QueryWrapper<>();
wrapper.eq("phone",username);
User user = userService.selectOne(wrapper);
if(user != null){
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
// 设置登录账号的角色
authorities.add(new SimpleGrantedAuthority("ROLE_vip"));
UserDetails user1 = new org.springframework.security.core.userdetails.User(user.getPhone(),new BCryptPasswordEncoder().encode(user.getPassword()),authorities);//密码需要加密
return user1;
}
return null;
}
}
SpringSecurityConfig :config 类
package com.example.subject.Config;
import com.example.subject.LiTu.service.impl.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource;
/**
* @author Nuisance
* @date 2020/8/30 11:59
*/
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Resource
private UserServiceImpl userService;
/**
* 授权
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
// .antMatchers("/LiTu/**").permitAll();
.antMatchers("/LiTu/**").hasRole("vip");//身份授权
//定制登录页面(/toLogin)
http.formLogin().loginPage("/toLogin").successForwardUrl("/LiTu/");
http.csrf().disable();//关闭CSRF功能
http.logout().logoutSuccessUrl("/toLogin");
http.rememberMe().rememberMeParameter("remember");
}
/**
* 认证
* @param auth
* @throws Exception
*/
//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());//认证,设置加密方式
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
常见原因分析:
1、没有设置加密,出警告,且无法验证:Encoded password does not look like BCrypt;
在service,和config类都加上就行了;
2、User:
UserDetails user1 = new org.springframework.security.core.userdetails.User(user.getPhone(),new BCryptPasswordEncoder().encode(user.getPassword()),authorities);
//注意这里面的User类是哪里的