一、整合springSecurity
引入pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
config配置类
@EnableMethodSecurity
@Configuration
public class MySecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
//请求授权
httpSecurity.authorizeHttpRequests(registry->{
registry.requestMatchers("/").permitAll()//首页都能访问
.anyRequest().authenticated();//除首页外都需要认证
});
//表单登录:使用springSecurity默认表单登录
//httpSecurity.formLogin();
//使用自己的登录
httpSecurity.formLogin(httpSecurityFormLoginConfigurer -> {
httpSecurityFormLoginConfigurer.loginPage("/login").permitAll();//自定义登录页位置
});
return httpSecurity.build();
}
//查询用户详情
@Bean
UserDetailsService userDetailsService(PasswordEncoder passwordEncoder){
UserDetails laowang = User.withUsername("laowang")
.password(passwordEncoder.encode("123456"))//密码必须加密
.roles("admin")
.authorities("file_read")
.build();
UserDetails zhangsan = User.withUsername("zhangsan")
.password(passwordEncoder.encode("123456"))
.roles("admin","hr")
.authorities("file_write")
.build();
//模拟内存中保存所有用户信息
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(laowang,zhangsan);
return manager;
}
//密码加密器
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
前端界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>你好呀</h1>
</body>
</html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
<title>Spring Security Example</title>
</head>
<body>
<div th:if="${param.error}">Invalid username and password.</div>
<div th:if="${param.logout}">You have been logged out.</div>
<form th:action="@{/login}" method="post">
<div>
<label> User Name : <input type="text" name="username" /> </label>
</div>
<div>
<label> Password: <input type="password" name="password" /> </label>
</div>
<div><input type="submit" value="登录" /></div>
</form>
</body>
</html>
controller层
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello";
}
@PreAuthorize("hasAuthority('file_write')")
@GetMapping("/filed")
public String filed(){
return "获取写权限";
}
}
@Controller
public class LoginController {
@GetMapping("/login")
public String login(){
return "login";
}
}
通过springboot配置文件配置
spring.security.user.name=laowang
spring.security.user.password=123456
spring.security.user.roles=admin,hr