Springboot实现登录功能(token、redis、登录拦截器、全局异常处理)
以下是一个简化的Spring Boot实现登录功能的例子,包括使用Token、Redis以及登录拦截器和全局异常处理。
// UserController.java
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
� private UserService userService;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
String token = userService.login(loginRequest);
return ResponseEntity.ok(new AuthResponse(token));
}
// 其他API端点...
}
// UserService.java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private RedisTemplate<String, String> redisTemplate;
public String login(LoginRequest loginRequest) {
// 验证用户凭证
User user = userRepository.findByUsername(loginRequest.getUsername());
if (user != null && BCrypt.checkpw(loginRequest.getPassword(), user.getPassword())) {
String token = UUID.randomUUID().toString();
// 将token存储到Redis,设置过期时间
redisTemplate.opsForValue().set(token, user.getUsername(), 10, TimeUnit.MINUTES);
return token;
}
throw new AuthenticationException("登录失败");
}
// 其他业务逻辑方法...
}
// LoginInterceptor.java
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
if (token != null && redisTemplate.hasKey(token)) {
String username = redisTemplate.opsForValue().get(token);
UserDetails userDetails = User.withUsername(username).password("").authorities("USER").build();
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
return true;
}
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return false;
}
}
// GlobalExceptionHandler.java
@ControllerAdvice
public class GlobalExceptionHa
评论已关闭