下面将为您详细讲解Spring Security从数据库中获取用户信息进行验证的攻略。
什么是Spring Security
Spring Security是一个功能强大、可高度定制的认证和授权框架,可用于保护基于Spring的Java应用程序。它提供了基于角色、用户和访问级别的身份验证和授权,以及多种身份验证选项,包括基本身份验证、OAuth和JWT等。
从数据库中获取用户信息进行验证
Spring Security提供了从数据库中获取用户信息进行认证的功能,使得用户登录时的认证可以更加灵活地进行管理。
实现从数据库中获取用户信息验证的步骤如下:
- 添加Spring Security依赖和数据库依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
- 在application.properties中配置数据库信息
spring.datasource.url=jdbc:mysql://localhost:3306/security
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- 创建UserDetails实体类
public class SecurityUser implements UserDetails {
private Integer id;
private String username;
private String password;
private boolean enabled;
// ... 省略getter、setter
}
- 实现UserDetailsService接口
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.getByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在!");
}
SecurityUser securityUser = new SecurityUser();
securityUser.setId(user.getId());
securityUser.setUsername(user.getUsername());
securityUser.setPassword(user.getPassword());
securityUser.setEnabled(user.getEnabled() == 1);
return securityUser;
}
}
- 创建WebSecurityConfigurerAdapter配置类
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
http.formLogin().loginPage("/login").defaultSuccessUrl("/index").permitAll();
http.logout().permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/static/**");
}
}
- 编写登录页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="/login" method="post">
<div>
<label for="username">用户名:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">密码:</label>
<input type="password" id="password" name="password" required>
</div>
<div>
<input type="submit" value="登录">
</div>
</form>
</body>
</html>
示例演示
下面是两条使用Spring Security从数据库中获取用户信息进行验证的示例:
示例一:电商网站登录验证
电商网站为用户提供了注册和登录功能。用户注册后,其信息会被存储在数据库中。用户登录时,程序从数据库中获取用户信息进行验证。如果验证成功,就将用户的登录信息存储在Session中,并跳转到个人中心页面;如果验证失败,就返回登录页面并显示错误提示。
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public String doLogin(String username, String password, HttpSession session) {
User user = userService.getByUsername(username);
if (user == null || !user.getPassword().equals(password)) {
return "login";
}
session.setAttribute("userId", user.getId());
return "redirect:/user/center";
}
@GetMapping("/user/center")
public String center(HttpSession session, Model model) {
Integer userId = (Integer) session.getAttribute("userId");
if (userId == null) {
return "login";
}
User user = userService.getById(userId);
model.addAttribute("user", user);
return "center";
}
// ... 省略其他方法
}
示例二:活动报名网站验证
活动报名网站允许用户报名参加、发布活动。用户登录后,其信息会被存储在数据库中。在用户报名参加活动时,程序从数据库中获取用户信息进行验证。如果验证成功,就将用户的报名信息存储在数据库中;如果验证失败,就返回登录页面并显示错误提示。
@Controller
public class ActivityController {
@Autowired
private ActivityService activityService;
@Autowired
private UserService userService;
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public String doLogin(String username, String password, HttpSession session) {
User user = userService.getByUsername(username);
if (user == null || !user.getPassword().equals(password)) {
return "login";
}
session.setAttribute("userId", user.getId());
return "redirect:/activity/list";
}
@GetMapping("/activity/register/{activityId}")
public String register(@PathVariable Integer activityId, HttpSession session, Model model) {
Integer userId = (Integer) session.getAttribute("userId");
if (userId == null) {
return "login";
}
Activity activity = activityService.getById(activityId);
if (activity == null) {
return "notfound";
}
User user = userService.getById(userId);
model.addAttribute("activity", activity);
model.addAttribute("user", user);
return "register";
}
@PostMapping("/activity/register")
public String doRegister(Integer activityId, Integer userId) {
Activity activity = activityService.getById(activityId);
User user = userService.getById(userId);
if (activity == null || user == null) {
return "notfound";
}
activityService.register(activity, user);
return "redirect:/activity/list";
}
// ... 省略其他方法
}
以上就是使用Spring Security从数据库中获取用户信息进行验证的完整攻略,如果有疑问,请随时提出。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringSecurity从数据库中获取用户信息进行验证的案例详解 - Python技术站