springboot整合spring security 实现用户登录注册与鉴权全记录,权限从数据库中查询
时间: 2024-05-01 21:17:06 浏览: 278
首先,需要在pom.xml中加入spring security和相关依赖文件:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
</dependency>
```
接着,在application.properties中配置数据库信息:
```
spring.datasource.url=jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
```
然后,创建用户表和权限表,用来存储用户和权限信息。用户表包括用户名和密码,权限表包括权限名称和对应的URL。
接下来,创建UserDetailService实现类,用于从数据库中读取用户信息。代码如下:
```
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
User user = userDao.findByUserName(userName);
if (user == null) {
throw new UsernameNotFoundException("用户名不存在");
}
List<GrantedAuthority> authorities = new ArrayList<>();
List<Role> roles = user.getRoles();
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
}
return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), authorities);
}
}
```
然后,创建SecurityConfig类,用于配置Spring Security。代码如下:
```
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
其中,configure方法用于配置请求的权限,configureGlobal方法用于设置自定义的UserDetailsService,passwordEncoder方法用于设置密码加密方式。
最后,创建UserController类,用于处理用户登录注册和鉴权请求。代码如下:
```
@RestController
public class UserController {
@Autowired
private UserDao userDao;
@Autowired
private PasswordEncoder passwordEncoder;
@PostMapping("/register")
public String register(@RequestParam String userName, @RequestParam String password) {
User user = userDao.findByUserName(userName);
if (user != null) {
return "用户名已存在";
}
user = new User();
user.setUserName(userName);
user.setPassword(passwordEncoder.encode(password));
userDao.save(user);
return "注册成功";
}
@PostMapping("/login")
public String login(@RequestParam String userName, @RequestParam String password) {
try {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, password);
Authentication authentication = authenticationManager().authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
return "登录成功";
} catch (Exception e) {
return "用户名或密码错误";
}
}
@GetMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public String admin() {
return "管理员权限";
}
@GetMapping("/user")
@PreAuthorize("hasAnyRole('USER','ADMIN')")
public String user() {
return "用户权限";
}
}
```
其中,register方法用于处理用户注册请求,login方法用于处理用户登录请求,admin和user方法用于处理鉴权请求。
至此,整合spring security实现用户登录注册与鉴权全记录,权限从数据库中查询的操作已经完成。
阅读全文