本文主要的功能:
·一、使用springsecurity默认的验证账号以及密码验证机制
二、修改springsecurity默认的验证账号以及密码
三、配置文件方式修改springsecurity默认的验证账号以及密码
四、整合自己数据库进行认证
一、使用springsecurity默认的验证账号以及密码验证机制
1、创建springboot项目,导入依赖;
org.springframework.boot spring-boot-starter-security
2、创建controller启动项目报错,显示没有进行数据源的配置,因为springsecurity进行认证的时候默认是需要创建临时的数据表的;
@RestController @RequestMapping("/test2") public class Controller { @GetMapping("/hello_word") public String test(){ System.out.println("hello"); return "hello world"; } }
Description: Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. Reason: Failed to determine a suitable driver class
3、引入远程连接数据库数据源依赖,在springboot配置文件中进行配置;
mysql mysql-connector-java
#连接数据库 ###mysql 连接信息,test是数据库名 spring.datasource.url=jdbc:mysql://ip地址:3306/数据库名称?serverTimezone=GMT%2B8 ###用户名 spring.datasource.username=账号 ###密码 spring.datasource.password=密码 ###驱动 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
4、启动项目,访问controller,访问http://localhost:8080/test2/hello word;使用默认账号user,密码在控制台进行登录;
Using generated security password: f601ae18-7838-466f-bc90-ab9d2eb011a6
5、启动项目,访问controller,访问http://localhost:8080/test2/hello word;使用默认账号user,密码在控制台进行登录;
二、修改springsecurity默认的验证账号以及密码
1、配置文件修改参数,重新访问controller,输入现有账号密码登录;
spring.security.user.name=pxq spring.security.user.password=pxq
三、配置文件方式修改springsecurity默认的验证账号以及密码
1、书写配置类继承WebSecurityConfigurerAdapter重写configure方法;报错
@Configuration //需要添加注解不然配置不生效 public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("zyf").password("zyf"); } }
security在在验证时会调用UserDetailsService的loadUserByUsername()方法,这里没用自定义,使用的是基于内存的验证auth.inMemoryAuthentication(),配置类中配置自定义用户但没有设置用户的角色,不设置角色就会报这个异常;(可以看下源码部分)
nested exception is java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority collection
2、重写书写配置类后依旧报错;
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("zyf").password("zyf").roles("admin"); } }
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id “null”
3、最终的配置方案,再次访问可以成功访问;
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); String encode = bCryptPasswordEncoder.encode("zyf"); auth.inMemoryAuthentication().withUser("zyf").password(encode).roles("admin"); } @Bean PasswordEncoder get(){ return new BCryptPasswordEncoder(); } }
四、整合自己数据库进行认证
1、创建用户数据库数据库
USE `springsecuritytest2`; DROp TABLE users; CREATE TABLE IF NOT EXISTS `users`( `id` INT UNSIGNED AUTO_INCREMENT, `username` VARCHAR(100) NOT NULL, `password` VARCHAR(400) NOT NULL, PRIMARY KEY ( `id` ) )ENGINE=INNODB DEFAULT CHARSET=utf8; INSERT INTO users ( id,username,`password`) VALUES ( 1, "pxq","pxq"); SELECT * FROM users;
2、创建实体类,这边需要用到注解,需要引入lombok依赖
@Data @AllArgsConstructor @NoArgsConstructor public class Users { private Integer id; private String username; private String password; }
org.projectlombok lombok
3、由于这边需要对数据库进行查找 *** 作,所以需要整合Mybatis-Plus;引入依赖,创建包mapper,编写接口UserMapper继承baseMapper<要操作的泛型>;之后如果要 *** 作数据库,只需要注入UserMapper实例;
com.baomidou mybatis-plus-boot-starter3.0.5
@Repository public interface UserMapper extends baseMapper{ }
4、测试Mybatis,报如下错误,需要在主程序上添加包扫描,来扫描编写的mapper接口包,重写测试,完美通过;
@SpringBootTest class Springcloudtest2ApplicationTests { @Autowired private UserMapper userMapper; @Test void contextLoads() { Users users = userMapper.selectById(1); System.out.println(users); } }
错误:java.lang.IllegalArgumentException: At least one base package must be specified
@SpringBootApplication @MapperScan("com.example.springcloudtest2.mapper") public class Springcloudtest2Application { public static void main(String[] args) { SpringApplication.run(Springcloudtest2Application.class, args); } }
5、想要用我们自己的数据库进行账号密码登录,我们就需要你去实现UserDetailsService接口,重写方法loadUserByUsername;
public class MyUserDeatilsService implements UserDetailsService { @Autowired private UserMapper userMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // 这边和之前一样需要进行权限的配置,不然那会报错,先赋值默认,也可以放在数据库 Listauthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");//ROLE_sale QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("username",username); Users users = userMapper.selectOne(queryWrapper); if(users == null){ throw new UsernameNotFoundException("用户名不存在"); } User user = new User(users.getUsername(), users.getPassword(), authorities); // this(username, password, true, true, true, true, authorities); return user; } }
6、重新编写配置文件,原先我们通过auth.inMemoryAuthentication().withUser,现在我们通过auth.userDetailsService(myUserDeatilsService).passwordEncoder(get());添加上自己数据库的判断,找不到抛出异常,找到了返回对象UserDetails;
@Configuration public class SecurityConfig1 extends WebSecurityConfigurerAdapter { @Autowired private MyUserDeatilsService myUserDeatilsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 这边是我们原来自定义账号密码 // BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); // String encode = bCryptPasswordEncoder.encode("zyf"); // auth.inMemoryAuthentication().withUser("zyf").password(encode).roles("admin"); // 现在我们通过 auth.userDetailsService(myUserDeatilsService).passwordEncoder(get()); } @Bean PasswordEncoder get(){ return new BCryptPasswordEncoder(); } }
7、运行报错;原因:返回的UserDetails对象的密码需要进行加密;更改为下面,成功测试通过
Encoded password does not look like BCrypt;
User user = new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), authorities);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)