写出使用springboot 注解加拦截器实现权限认证代码
时间: 2024-05-01 09:18:17 浏览: 157
好的,以下是使用Spring Boot注解与拦截器实现权限认证的代码示例:
1. 创建自定义拦截器:
```java
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 在此处实现权限认证逻辑
String token = request.getHeader("Authorization");
if(token == null || token.isEmpty()) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
return false;
}
// 验证通过,放行
return true;
}
}
```
2. 创建配置类:
```java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private AuthInterceptor authInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/login", "/register");
}
}
```
3. 在Controller类或方法上标注注解:
```java
@RestController
@RequestMapping("/api")
public class MyController {
// 标注注解,需要认证权限
@GetMapping("/userinfo")
@AuthRequired
public String getUserInfo() {
// 实现获取用户信息逻辑
return "UserInfo";
}
}
```
4. 创建自定义注解:
```java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthRequired {
}
```
5. 在拦截器中获取自定义注解:
```java
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 获取请求处理方法的所有注解
Method method = ((HandlerMethod)handler).getMethod();
Annotation[] annotations = method.getDeclaredAnnotations();
// 遍历注解数组,寻找 AuthRequired 注解
boolean authRequired = false;
for(Annotation annotation : annotations) {
if(annotation.annotationType() == AuthRequired.class) {
authRequired = true;
break;
}
}
if(authRequired) {
// 需要认证权限的逻辑处理
}
// 验证通过,放行
return true;
}
```
以上就是使用Spring Boot注解与拦截器实现权限认证的简单示例代码。请注意,在实际项目中,需要根据具体需求进行修改和完善。