介绍
原本配置折磨,springboot整合十分轻松,登陆,权限,还能网络安全
体验
创建springboot项目
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
实现controller
@RestController
public class HelloSecurity {
@RequestMapping("/hello")
public String hello(){
return "hello security";
}
}
登陆验证
当你使用http://localhost:8080/hello会重定向到http://localhost:8080/login
登录
随机生成密码
默认用户名:user
密码:
yaml自定义密码
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
username: root
password: 123456
security:
user:
name: root
password: root
代码类config设置
首先config配置
/**
* @author 伍六七
* @date 2022/9/7 12:22
*/
@Configuration
public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {
/**
* 添加认证
* withUser--添加用户
* password--设置密码
* roles--设置能访问的请求路径
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")//添加用户admin
.password("{noop}admin")// 不设置密码加密
.roles("ADMIN","USER")// 添加角色为admin,user
.and()
.withUser("user")
.password("{noop}user")
.roles("USER")
.and()
.withUser("tmp")
.password("{noop}tmp")
.roles();
}
/**
* 添加权限
* .antMatchers("/product/**").hasRole("USER")
* 能访问的请求需要什么角色的权限
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/product/**").hasRole("USER")//添加/product/** 下的所有请求只能由user角色才能访问
.antMatchers("/admin/**").hasRole("ADMIN")//添加/admin/** 下的所有请求只能由admin角色才能访问
.anyRequest().authenticated()// 没有定义的请求,所有的角色都可以访问(tmp也可以)。
.and()
.formLogin().and()
.httpBasic();
}
}
按照不同权限的路径去设置请求
/**
* 需要管理员权限
* @author 伍六七
* @date 2022/9/7 12:41
*/
@RestController
@RequestMapping("/admin")
public class AdminController {
@RequestMapping("/hello")
public String hello(){
return "THIS IS ADMIN HTML!";
}
}
/**
* 需要用户权限
* @author 伍六七
* @date 2022/9/7 12:41
*/
@RestController
@RequestMapping("/product")
public class ProductController {
@RequestMapping("/hello")
public String hello(){
return "hTHIS IS PRODUCT HTML!";
}
}
/**
* 所有权限即可
* @author 伍六七
* @date 2022/9/7 10:41
*/
@RestController
public class HelloSecurity {
@RequestMapping("/hello")
public String hello(){
return "hello security";
}
}
通过上面的设置,访问http://localhost:8080/admin/hello只能由admin访问,http://localhost:8080/product/hello admin和user都可以访问,http://localhost:8080/hello 所有用户(包括tmp)都可以访问。
使用数据库的用户名、密码登录
建表
默认角色前缀必须是ROLE_,因为spring-security会在授权的时候自动使用match中的角色加上ROLE_后进行比较。
CREATE TABLE `users` (
`id` int(28) NOT NULL,
`login` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
`role` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
INSERT INTO `users`(`id`, `login`, `password`, `role`) VALUES (1, 'user', 'user', 'ROLE_USER');
INSERT INTO `users`(`id`, `login`, `password`, `role`) VALUES (2, 'admin', 'admin', 'ROLE_ADMIN');
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
添加yaml配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
username: root
password: 123456
配置config类
/**
* @author 伍六七
* @date 2022/9/7 13:16
*/
@Configuration
public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)//设置自定义userDetailsServiceImpl
.passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/product/**").hasRole("USER")
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic()
.and()
.logout().logoutUrl("/logout");
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();// 使用不使用加密算法保持密码
// return new BCryptPasswordEncoder();
}
}
加密
/**
*加密
*/
@Test
void encode(){
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String password = bCryptPasswordEncoder.encode("user");
String password2 = bCryptPasswordEncoder.encode("admin");
System.out.println(password);
System.out.println(password2);
}
UserDetailsService-验证
调用UserDetailsService的实现类去查找用户