SpringBoot 权限拦截:不使用Shiro 实现权限控制
SpringBoot 中可以使用拦截器或者过滤器的机制来实现权限拦截。具体实现步骤如下:
- 创建一个拦截器或者过滤器类,实现 HandlerInterceptor 或者 Filter 接口。
- 在拦截器或者过滤器中实现权限控制逻辑。
- 在 SpringBoot 中注册拦截器或者过滤器。
- 在需要进行权限控制的接口上添加拦截器或者过滤器。
下面是一个简单的示例:
- 创建一个拦截器类,实现 HandlerInterceptor 接口。
@Component
public class PermissionInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 获取用户信息和请求路径
User user = (User) request.getSession().getAttribute('user');
String uri = request.getRequestURI();
// 判断用户是否有权限访问该接口
if (user == null || !user.hasPermission(uri)) {
response.setStatus(HttpStatus.FORBIDDEN.value());
return false;
}
return true;
}
}
- 在 SpringBoot 中注册拦截器。
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private PermissionInterceptor permissionInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(permissionInterceptor)
.addPathPatterns("/api/**"); // 拦截/api路径下的所有接口
}
}
- 在需要进行权限控制的接口上添加拦截器。
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/user")
public User getUser() {
// ...
}
@GetMapping("/admin")
public String getAdmin() {
// ...
}
// ...
}
在上面的例子中,只有具有访问 /api/admin 接口权限的用户才能访问该接口,否则返回 403 错误。
原文地址: https://www.cveoy.top/t/topic/oaAw 著作权归作者所有。请勿转载和采集!