小明:嘿,小红,我们学校要上线一个迎新系统,你负责实现统一身份认证功能吗?
小红:是的,我负责这部分。我们需要确保每位新生注册后能够安全地访问系统内的各项服务。你有什么好的建议吗?
小明:我们可以使用JWT(JSON Web Tokens)来实现。首先,我们需要创建一个用户表来存储新生的信息。
小红:好主意,那我们先创建一个用户表吧。
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
);
]]>
小明:接下来,我们需要编写一个注册接口,用于接收新生提交的信息并将其保存到数据库中。
@PostMapping("/register")
public ResponseEntity> registerUser(@RequestBody User user) {
if (userRepository.findByUsername(user.getUsername()).isPresent()) {
return ResponseEntity.badRequest().body("用户名已存在");
}
if (userRepository.findByEmail(user.getEmail()).isPresent()) {
return ResponseEntity.badRequest().body("邮箱已存在");
}
user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepository.save(user);
return ResponseEntity.ok().build();
}
]]>
小红:注册功能完成后,我们还需要实现登录验证功能,确保新生能通过身份验证。
@PostMapping("/login")
public ResponseEntity> authenticateUser(@RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
);
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = tokenProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
}
]]>
小明:最后,我们需要确保每次请求都能正确验证用户的JWT令牌。
@PreAuthorize("hasRole('ROLE_USER')")
@GetMapping("/protected")
public ResponseEntity> getProtectedData() {
return ResponseEntity.ok("这是受保护的数据");
}
]]>