springboot使用JWT和拦截器实现登录验证
时间: 2024-03-03 09:47:10 浏览: 150
下面是一个使用 Spring Boot、JWT 和拦截器实现登录验证的示例代码:
1. 添加 JWT 依赖
在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
```
2. 创建 JWT 工具类
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtUtil {
private final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
public String generateToken(String subject) {
return Jwts.builder()
.setClaims(new HashMap<>())
.setSubject(subject)
.setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000))
.signWith(key)
.compact();
}
public boolean validateToken(String token) {
try {
Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
public String getUsernameFromToken(String token) {
Claims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
return claims.getSubject();
}
}
```
3. 创建拦截器
```java
import com.example.demo.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
private JwtUtil jwtUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
if (token != null && jwtUtil.validateToken(token)) {
String username = jwtUtil.getUsernameFromToken(token);
request.setAttribute("username", username);
return true;
} else {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
if (loginRequired != null && modelAndView != null) {
modelAndView.addObject("username", request.getAttribute("username"));
}
}
}
```
4. 创建注解
```java
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LoginRequired {
}
```
5. 创建控制器
```java
import com.example.demo.interceptor.LoginRequired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/")
public String index() {
return "Hello World";
}
@GetMapping("/hello")
@LoginRequired
public String hello() {
return "Hello " + SecurityContextHolder.getContext().getAuthentication().getName();
}
}
```
6. 配置拦截器
```java
import com.example.demo.interceptor.AuthenticationInterceptor;
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 WebMvcConfig implements WebMvcConfigurer {
@Autowired
private AuthenticationInterceptor authenticationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticationInterceptor).addPathPatterns("/**");
}
}
```
7. 创建登录控制器
```java
import com.example.demo.jwt.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class LoginController {
@Autowired
private JwtUtil jwtUtil;
@PostMapping("/login")
public Map<String, Object> login(@RequestBody Map<String, String> params) {
String username = params.get("username");
String password = params.get("password");
// TODO: 验证用户名和密码
String token = jwtUtil.generateToken(username);
Map<String, Object> result = new HashMap<>();
result.put("token", token);
return result;
}
}
```
在这个示例中,我们创建了一个 JWT 工具类来生成和验证 JWT,创建了一个拦截器来验证用户是否登录,并使用 @LoginRequired 注解来标记需要登录验证的方法。我们还创建了一个登录控制器来生成 JWT。通过这个示例,您可以了解如何使用 Spring Boot、JWT 和拦截器实现登录验证。
阅读全文