java - spring rest API 的所有查询的自定义验证
问题描述
我正在使用 Spring Rest API,并且我想HttpServletRequest
在进入 rest api 查询之前应用自定义验证(更具体地说,我想检查用户是否经过身份验证,因为我也需要对象)。
例如,我有 3 个 API。1.RestAPI/test1 2.RestAPI/test2 3.RestAPI/test3
所以在进行查询之前,我想检查用户是否经过身份验证。
我可以用ConstraintValidator
吗?
我怎样才能做到这一点?
我没有使用弹簧靴......
谢谢!
解决方案
有以下方法可以做到:
1)弹簧安全@PreAuthorize("isAuthenticated()")
或@Secured("ROLE_ADMIN")
有关更多信息,请参阅线程
2)您可以创建自定义注释,添加方面并SecurityContextHolder
签入:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Authenticated {
}
import org.aspectj.lang.annotation.Aspect;
@Aspect
@Component
public class AuthenticatedAspect {
@Around("@annotation(Authenticated)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
if (!SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
throw your exeption
}
return joinPoint.proceed();
}
}
对于第二种方法,您可能需要添加proxy-target-class="true"
<aop:aspectj-autoproxy proxy-target-class="true"/>
推荐阅读
- machine-learning - 遇险清单中的线性回归模型
- android - 将旧 EditTexts 的内容保存在 RecyclerView 中
- javascript - react-modal 动态调整大小
- mysql - 使用 UNION ALL 或 DISTINCT 或 NOT IN 的正确方法
- python-3.x - 从 web2py 中的 SQLFORM (SQLFORM.grid) 向引用表添加新的(缺少的)条目
- javascript - React Native:使用内置按钮时出错
- java - 分页:重定向到相同的 URL 但替换单个参数
- adobe - 从 Photoshop 中自定义 CEP 面板的学习面板中打开特定教程
- c# - 如何在 xamarin android 中更改导航栏上的当前项目
- php - 按价格删除几乎重复的值