请给我一个在利用切面编程和jwt做登录操作的例子
时间: 2024-03-09 07:47:10 浏览: 29
好的,以下是一个使用切面编程和 JWT 实现登录操作的示例代码:
首先在 pom.xml 中添加 AOP 和 JWT 相关依赖,如下所示:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
```
然后定义一个切面类,如下所示:
```java
@Aspect
@Component
public class LoginAspect {
@Autowired
private JwtUtils jwtUtils;
@Pointcut("@annotation(com.example.demo.annotation.LoginRequired)")
public void loginRequired() {}
@Before("loginRequired()")
public void checkLogin() throws Exception {
String token = jwtUtils.getToken();
if (token == null) {
throw new Exception("未登录");
}
if (!jwtUtils.validateToken(token)) {
throw new Exception("登录已过期,请重新登录");
}
}
}
```
在切面类中,我们首先使用 `@Aspect` 注解标注该类为一个切面类,然后使用 `@Component` 注解将该类注入 Spring 容器中。接着,我们定义了一个切点 `loginRequired()`,用于匹配被 `@LoginRequired` 注解标注的方法。最后,在 `checkLogin()` 方法中,我们检查当前用户是否已登录,如果未登录或登录已过期,则抛出一个异常。
下面是一个使用了 `@LoginRequired` 注解的示例控制器类:
```java
@RestController
public class UserController {
@Autowired
private JwtUtils jwtUtils;
@RequestMapping("/login")
public String login() {
String token = jwtUtils.generateToken("admin");
return "登录成功,Token:" + token;
}
@LoginRequired
@RequestMapping("/user")
public String getUser() {
return "当前用户:" + jwtUtils.getUsername();
}
}
```
在上述控制器类中,我们首先定义了一个 `/login` 接口,用于模拟登录操作。然后,我们在 `/user` 接口上使用了 `@LoginRequired` 注解,表示该接口需要登录才能访问。我们通过调用 `JwtUtils` 类中的方法获取当前用户的 Token 和用户名。
最后,我们需要定义一个 `JwtUtils` 类,用于生成和验证 JWT。示例代码如下:
```java
@Component
public class JwtUtils {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
public String generateToken(String username) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + expiration);
return Jwts.builder()
.setSubject(username)
.setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String getUsername() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication.getName();
}
public String getToken() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String header = request.getHeader("Authorization");
if (StringUtils.hasText(header) && header.startsWith("Bearer ")) {
return header.substring(7);
}
return null;
}
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
}
```
在上述 `JwtUtils` 类中,我们首先通过 `@Value` 注解将配置文件中的 JWT 密钥和过期时间注入到该类中。然后,我们定义了三个方法:
- `generateToken()` 方法用于生成 JWT。
- `getUsername()` 方法用于获取当前用户的用户名。
- `getToken()` 方法用于获取当前用户的 Token。
- `validateToken()` 方法用于验证当前用户的 Token 是否合法。
最后,在配置文件中添加 JWT 相关配置:
```yaml
jwt:
secret: mysecret
expiration: 3600000
```
在以上配置中,我们将 JWT 密钥设置为 `mysecret`,过期时间设置为 1 小时。
以上就是一个使用切面编程和 JWT 实现登录操作的示例代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)