SpringBoot整合token实现登录认证完整代码
时间: 2023-10-04 12:04:07 浏览: 93
好的,下面是完整的代码,您可以根据需要进行参考。
pom.xml:
```xml
<dependencies>
<!-- SpringBoot Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JWT 依赖 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>
```
User.java:
```java
public class User {
private String username;
private String password;
// getter 和 setter 略
}
```
Result.java:
```java
public class Result {
private Integer code;
private String message;
private Object data;
// getter 和 setter 略
public static Result success(Object data) {
Result result = new Result();
result.setCode(200);
result.setMessage("操作成功");
result.setData(data);
return result;
}
public static Result failure(String message) {
Result result = new Result();
result.setCode(500);
result.setMessage(message);
return result;
}
}
```
TokenUtil.java:
```java
public class TokenUtil {
private static final String SECRET_KEY = "your_secret_key"; // 密钥,可以自定义
// 生成token
public static String generateToken(String subject) {
Date now = new Date();
Date expiration = new Date(now.getTime() + 3600 * 1000); // 过期时间为1小时
return Jwts.builder()
.setSubject(subject)
.setIssuedAt(now)
.setExpiration(expiration)
.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
.compact();
}
// 验证token
public static boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
// 从token中获取用户名
public static String getUsernameFromToken(String token) {
Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
return claims.getSubject();
}
}
```
TokenRequired.java:
```java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TokenRequired {
}
```
TokenInterceptor.java:
```java
@Component
public class TokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization"); // 从请求头中获取token
if (StringUtils.isNotBlank(token) && TokenUtil.validateToken(token)) {
// 验证通过,放行请求
return true;
} else {
// 验证失败,返回错误信息
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("{\"code\":401,\"message\":\"未登录或登录已过期\"}");
out.flush();
out.close();
return false;
}
}
}
```
UserController.java:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping("/login")
public Result login(@RequestBody User user) {
// 根据用户名和密码验证用户身份
if (userService.validateUser(user.getUsername(), user.getPassword())) {
// 生成token并返回
String token = TokenUtil.generateToken(user.getUsername());
return Result.success(token);
} else {
return Result.failure("用户名或密码错误");
}
}
}
```
BookController.java:
```java
@RestController
@RequestMapping("/book")
public class BookController {
@GetMapping("/list")
@TokenRequired // 自定义注解,用于标识需要登录认证的接口
public Result list() {
List<Book> books = bookService.listBooks();
return Result.success(books);
}
}
```
WebMvcConfig.java:
```java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private TokenInterceptor tokenInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(tokenInterceptor).addPathPatterns("/**").excludePathPatterns("/user/login");
}
}
```
其中,userService和bookService需要您自己实现。另外,为了简化代码,省略了Book类的定义。
阅读全文