一、引入依赖
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.34.0</version>
</dependency>
二、增加拦截器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebSecurityConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor)
.addPathPatterns("/api/**") // 拦截所有请求
.excludePathPatterns("/api/auth/login", "/api/auth/logout"); // 排除登录和登出接口
}
}
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 检查是否为登录接口
String requestURI = request.getRequestURI();
if (requestURI.equals("/api/auth/login")) {
return true; // 登录接口不需要拦截
}
// 检查用户是否登录
if (StpUtil.isLogin()) {
return true; // 用户已登录,放行请求
} else {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().write("unauthorized: no login");
response.getWriter().flush();
return false; // 拦截请求
}
}
}
三、校验类
import cn.dev33.satoken.stp.StpUtil;
import org.ethh.common.enums.ErrorCode;
import org.ethh.marketMakerManager.model.Response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private UserService userService;
@PostMapping("/login")
public ApiResponse<LoginInfo> login(@RequestParam String username, @RequestParam String password) {
User user = userService.getUserByUsername(username);
LoginInfo loginInfo = new LoginInfo();
if (user != null && user.getPassword().equals(password)) {
// 登录成功,生成 Token
StpUtil.login(username);
loginInfo.setToken(StpUtil.getTokenValue());
loginInfo.setResult("login success");
return ApiResponse.success(loginInfo);
}
loginInfo.setResult("login fail,用户名或密码错误");
return ApiResponse.failureWithDetails(ErrorCode.INTERNAL_ERROR,loginInfo);
}
@GetMapping("/logout")
public ApiResponse<LoginInfo> logout() {
LoginInfo loginInfo = new LoginInfo();
StpUtil.logout(); // 登出
loginInfo.setResult("logout success");
return ApiResponse.success(loginInfo);
}
@GetMapping("/userInfo")
public String getUserInfo() {
// 获取用户信息
String username = StpUtil.getLoginIdAsString();
return "当前登录用户: " + username;
// return "当前登录用户: " + "1";
}
}
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class UserService {
private static final Map<String, User> userMap = new HashMap<>();
static {
// 模拟用户数据,实际项目中应从数据库中获取
userMap.put("admin", new User("admin", "123456")); // 用户名: test,密码: 123456
}
public User getUserByUsername(String username) {
return userMap.get(username);
}
}
public class User {
private String username;
private String password; // 实际项目中密码应该加密存储
// 构造函数、getter 和 setter
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@ApiModel(description = "登录信息")
public class LoginInfo {
@ApiModelProperty(notes = "登录结果")
String result;
@ApiModelProperty(notes = "Token值")
String token;
}
最基本的登录系统